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.
Yes
No
No, it initializes
ptr
with thechar*
thatbuf
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 seenbuf
yet.Compare with these:
OK:
Error: