c++ – int x = x; What will happen?

Question:

What happens as a result of this instruction:

int x = x;

?

Answer:

If x is already defined in the given scope, this will not compile:

int x = 0;
int x = x; // <-- ошибка, повторная декларация переменной

http://ideone.com/3VGhe0

If there is no variable x in the given scope (for example, it is not defined at all, or it is defined in the outer scope), then this will compile, but the program will have undefined behavior . This means that you are not even guaranteed that there will be some garbage in the variable. The program has the right to do whatever it wants: from the point of view of the compiler, it is meaningless. Never do this: the C++ compiler thinks you're old enough and responsible enough to check that you're following the rules.


Yes, I don't know why the compiler doesn't throw an error in this case. Other languages ​​trust the programmer less and control.

Scroll to Top