Search code examples
c++cinitializationundefined-behavior

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


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++;

Solution

  • 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.