Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why printf() is printing 0 instead of 10 in following code? [duplicate]

Tags:

c

variables

linux

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 ?

like image 954
Chinna Avatar asked Apr 09 '14 05:04

Chinna


People also ask

Why printf in C is not working?

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.

How can I make printf print instantly?

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...

What is printf \n in C?

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.


3 Answers

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)

like image 61
Basile Starynkevitch Avatar answered Oct 06 '22 04:10

Basile Starynkevitch


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.

like image 20
tpb261 Avatar answered Oct 06 '22 02:10

tpb261


try this

#include<stdio.h>
main()
{
    int Var1=10;
   {
     char Var=Var1;
     printf("%d",Var);
   }
}
like image 20
Arsalan Qaiser Avatar answered Oct 06 '22 02:10

Arsalan Qaiser