Using newly declared variable in initialization (int x = x+1)?

With the expression:

int x = x + 1;

the variable x comes 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 x that comes into existence has an arbitrary value.

C++03 has this to say:

The point of declaration for a name is immediately after its complete declarator (clause 8) and before its initializer (if any) …

Example:
int x = 12;
{ int x = x; }
Here the second x is initialized with its own (indeterminate) value.

That second case there is pretty much what you have in your question.

Leave a Comment