clang++ - Declaration in if statement weird behaviour (C++) -
this question has answer here:
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 x should 1, 1. however, output is:
1818935350 32767 anyone know what's going on here? compiled clang-800.0.42.1
edit: tried following code bit tweak, , behaves expected.
int x = 1; if (int y = x) { printf("%d\n", y); if (int z = x) { printf("%d\n", z); } } one guess when use variable on rhs of declaration inside if statement, might not refer variable same name declared @ parent scope, instead it's referring variable that's being defined...
when int x = x, both x's refer same int. is, 1 declaring right there in line. initializing x itself, undefined behavior, since (of course) not initialized. x initialized 1 never printed in code, since declared in parent scope , shadowed ones in inner scopes.
Comments
Post a Comment