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?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With