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?