Increment pointer in if condition (pointer)

I am reading C ++ code where the developer often uses this type of template:

float *_array;

//...
while (expression) {

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

The outer while loop will end no matter what _array points to. My question is about conditions if (_array)and increment in this section.

At first, I thought that he should check to see if the pointer pointed to an "array", but this is not like the 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". Therefore, it if (pointer)is evaluated as true, even if the pointer exceeded a certain length of the array.

But what else could be the goal if (pointer)in this context?

+4
source share
6

- , _array NULL , .. , NULL.

new throws std::bad_alloc , , NULL. malloc, calloc, realloc new(std::nothrow), , NULL. NULL.

+6

C ++ true, NULL false, NULL.

if (ptr) ... if (ptr != NULL) ....

, NULL- .

+3

false, true.

,

if(_array != NULL)

if(_array)

ยง 4.12

, , prvalue bool. , ; true. std:: nullptr_t prvalue bool; false.

+2

- , NULL.

#include <iostream>
using namespace std;

int main()
{
    float *ptr = nullptr;

    for(int i = 0; i < 5; ++i)
    {
        cout << (ptr ? "ok" : "no") << endl;
        ++ptr;
    }

    cin.get();
}

:

no
ok
ok
ok
ok

, . if(ptr), NULL, NULL .

+1

: undefined.

6 , p undefined. , , .

, " " ++, undefined, , , .

+1

, C, if , zero non-zero. NULL 0, if! , NULL

Proof

#include <stdio.h>
int main()
{
    int *p = NULL;
    int a = 1;

    printf("%p %d\n", p, p);

    p = &a;
    printf("%p %d\n", p, p);

    return 0;
}

, :

$> gcc null.c
$> ./a.out
(nil) 0
0x7fff0556ff3c 89587516

, printf, % d, p zero. , if, , NULL -NULL.

In addition, I would like to add that use is made from standard best practices. This is the preferred method of checking if the pointer is NULL compared to potentially dangerous and error prone:

if (p == NULL) {
}

which may be mistakenly entered (dangerous) in:

if (p = NULL) {
}
0
source

Source: https://habr.com/ru/post/1584712/


All Articles