I just stumbled upon a behavior which surprised me:
When writing:
int x = x+1;
in a C/C++-program (or even more complex expression involving the newly created variable x) my gcc/g++ compiles without errors. In the above case X is 1 afterwards. Note that there is no variable x in scope by a previous declaration.
So I’d like to know whether this is correct behaviour (and even might be useful in some situation) or just a parser pecularity with my gcc version or gcc in general.
BTW: The following does not work:
int x++;
With the expression:
the variable
xcomes into existence at the=sign, which is why you can use it on the right hand side. By "comes into existence", I mean the variable exists but has yet to be assigned a value by the initialiser part.However, unless you’re initialising a variable with static storage duration (e.g., outside of a function), it’s undefined behaviour since the
xthat comes into existence has an arbitrary value.C++03 has this to say:
That second case there is pretty much what you have in your question.