Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++;
like image 945
Ansgar Lampe Avatar asked Mar 22 '12 10:03

Ansgar Lampe


People also ask

How do you initialize the variable?

Variables are explicitly initialized if they are assigned a value in the declaration statement. Implicit initialization occurs when variables are assigned a value during processing.

How do you initialize a variable in C++?

Variable initialization in C++ There are two ways to initialize the variable. One is static initialization in which the variable is assigned a value in the program and another is dynamic initialization in which the variables is assigned a value at the run time.


2 Answers

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.

like image 125
paxdiablo Avatar answered Oct 09 '22 06:10

paxdiablo


3.3.1 Point of declaration 1 The point of declaration for a name is immediately after its complete declarator (clause 8) and before its initializer (if any), except as noted below. [ Example: int x = 12; { int x = x; } Here the second x is initialized with its own (indeterminate) value. —end example ]

The above states so and should have indeterminate value, You are lucky with 1.

like image 28
Praveen Avatar answered Oct 09 '22 05:10

Praveen