c - Why printf() is printing 0 instead of 10 in following code? -
this question has answer here:
- c++ global , local variables 8 answers
if compile , run following code, printing 0 instead of 10.
#include<stdio.h> main() { int var=10; { char var=var; printf("%d",var); } } why printing 0 , why not 10 ?
because in local declaration
char var=var; the right occurrence of var refers local var, not upper one. alk commented, undefined behavior assign uninitialized variable.
so declaration not initialize var @ all, i.e. var contains garbage. in particular case, garbage happens 0.
btw, having 2 homonyms var in same function bad taste.
as this answer suggests, should compile gcc -wall -wshadow you'll warnings on code. (also add -g debug information able debug gdb)
Comments
Post a Comment