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

Popular posts from this blog

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

jsf - "PropertyNotWritableException: Illegal Syntax for Set Operation" error when setting value in bean -

laravel - Undefined property: Illuminate\Pagination\LengthAwarePaginator::$id (View: F:\project\resources\views\admin\carousels\index.blade.php) -