A.Stone A.Stone - 25 days ago 7
C++ Question

Declaration in if statement weird behaviour (C++)

I have following code:

int X = 1;
if (int X = X)
{
printf("%d\n", X);
if (int X = X)
{
printf("%d\n", X);
}
}


My expectation is X should be 1, 1. However, the output is:

1818935350
32767


Anyone know what's going on here? Compiled with clang-800.0.42.1

Edit: I tried the following code with a bit tweak, and now it behaves as I expected.

int X = 1;
if (int Y = X)
{
printf("%d\n", Y);
if (int Z = X)
{
printf("%d\n", Z);
}
}


One guess is when you use variable on RHS of a declaration inside if statement, it might not refer to the variable with the same name declared at parent scope, instead it's referring to the variable that's being defined...

Answer

When you say int X = X, both X's refer to the same int. That is, the one you are declaring right there in that line. So you are initializing X with itself, which is undefined behavior, since it was (of course) not already initialized. The X that you initialized with 1 is never printed in your code, since it is declared in a parent scope and shadowed by the ones in the inner scopes.