Initialization order: An array with a separate pointer to that same array

57 views Asked by At

I have a line of code that declares a static array of char, like so:

char buf[7];

I would like to traverse this array using a pointer, but buf itself obviously can't be incremented or decremented. My question is basically, is this legal, or is this undefined behavior:

// Does this guarantee ptr == buf?
char buf[7], *ptr = buf;

// ... because if not, then this could crash my program!
std::cout << *ptr << '\n';

This and similar examples compile and run just fine on my computer (WSL, gcc 9.3.0) with all optimization flags. In every test I've run, buf == ptr. But technically, would the compiler be allowed by the C++ standard to reorder these declarations so that ptr is initialized to some junk value?

I could obviously split this up into two lines and avoid any doubt, but I'm wondering if this one-line declaration is valid.

1

There are 1 answers

0
Ted Lyngmo On BEST ANSWER

is this legal

Yes

is this undefined behavior

No

would the compiler be allowed by the C++ standard to reorder these declarations so that ptr is initialized to some junk value?

No, it initializes ptr with the char* that buf decays into. If a compiler would be allowed to initialize them in the other order, it would need to fail compiling, since it wouldn't have seen buf yet.

Compare with these:

OK:

char buf[7];
char *ptr = buf;

Error:

char *ptr = buf;
char buf[7];