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 ?
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 ?
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
)
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.
try this
#include<stdio.h>
main()
{
int Var1=10;
{
char Var=Var1;
printf("%d",Var);
}
}