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 ?
Printf is not the thing being buffered, it's stdio, so all similar functions will behave in the same way. To demonstrate the buffering, all you have to do is printf a lot of characters, usually more than 1024, and printf will print as you will have exceeded the maximum buffer length and it will automatically fflush.
The output stream stdout is buffered by default, so if you want immediate output you'll need to flush the output stream - using fflush - or cause a newline to be printed in the printf : printf("Starting nets allocation..."); fflush(stdout); Or: printf("Starting nets allocation...
The escape sequence \n means newline. When a newline appears in the string output by a printf, the newline causes the cursor to position to the beginning of the next line on the screen.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With