c - Why printf() is printing 0 instead of 10 in following code? -


this question has answer here:

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

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -