What assumptions can I make for the local addresses of C ++ variables

I wonder if I can reuse a pointer to a variable inside a loop block.

int *ptr = nullptr;
for (int i = 0; i < 5; ++i) {
    int j = 5;
    if (!ptr) ptr = &j;
    cout << *ptr << endl;
}

I believe that this code will work on all compilers, but does it comply with the standards?

+4
source share
1 answer

No, that will not work.

The second iteration ptrindicates the jfirst iteration, which no longer exists. Highlighting ptrat this point is undefined behavior. The same for all iterations after the first.

+6
source

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


All Articles