6

If i compile and run the following code, it is printing 0 instead of 10.

#include<stdio.h>
main()
{
    int Var=10;
   {
     char Var=Var;
     printf("%d",Var);
   }
}

Why this is printing 0 and why not 10 ?

Chinna
  • 3,930
  • 4
  • 25
  • 55

3 Answers3

19

Because in local declaration

 char Var=Var;

the right occurrence of Var refers to the local Var, not the upper one. As Alk commented, this is undefined behavior to assign from an uninitialized variable.

So your declaration does not initialize Var at all, i.e. Var contains garbage. In your particular case, that garbage happens to be 0.

BTW, having two homonyms Var in the same function is really bad taste.

As this answer suggests, you should compile with gcc -Wall -Wshadow then you'll get some warnings on your code. (also add -g to get debug information to be able to debug with gdb)

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
8

Assuming you are using gcc, you would want to turn on -Wshadow (http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html). This would pop up an error, at the inner variable having same name as outer. The zero is a random value. It could print any garbage in that place.

tpb261
  • 255
  • 3
  • 12
  • You might consider deleting your answer now, since it has become redundant after [this](http://stackoverflow.com/a/22953927/2235132) was edited. – devnull Apr 09 '14 at 07:08
  • That answer has a link to this answer. Is it ok to delete? I don't know, is this even the right place to ask this question? – tpb261 Apr 09 '14 at 07:54
2

try this

#include<stdio.h>
main()
{
    int Var1=10;
   {
     char Var=Var1;
     printf("%d",Var);
   }
}
Arsalan Qaiser
  • 426
  • 2
  • 7
  • 26