Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment pointer within if (pointer) condition

I'm reading c++ code, where the developer often uses this kind of pattern:

float *_array;

//...
while (expression) {

    if (_array) {
        // ...
        _array += 1;
    } else {
        // ...
    }
}

The outer while loop will terminate independently from where _array points to. My question is about the if (_array) condition and the incrementation within that clause.

I first thought that it should check if the pointer "ran out of" the array, but that does not seem to be case. I tested it with this simple snippet:

float *p = new float[5];
int i = 0;
for (i = 0; i < 10; i++) {
    if (p) {
        std::cout << "ok\n";
    } else {
        std::cout << "no\n";
    }
    p += 1;
}

This will print 10 times "ok". So if (pointer) evaluates to true even if the pointer exceeded the defined array length.

But what else could be the purpose of if (pointer) in that context?

like image 956
basilikum Avatar asked Dec 10 '22 23:12

basilikum


2 Answers

Its purpose is to check whether pointer _array is pointing to NULL or not, i.e. to check if it is a NULL pointer.

new throws std::bad_alloc exception and therefore no need to check NULL. In case of malloc, calloc, realloc or new(std::nothrow), if the allocation fails they return NULL. In such case you need to check for NULL.

like image 93
haccks Avatar answered Dec 28 '22 05:12

haccks


In C and C++ a pointer when evaluated in a boolean context returns true if the pointer is not NULL and false if the pointer is NULL.

The form if (ptr) ... is a common shorthand for if (ptr != NULL) ....

This interpretation rule is true even if in the specific platform a NULL pointer is not represented by binary zeros.

like image 44
6502 Avatar answered Dec 28 '22 06:12

6502