#include <stdio.h>
void foo(void)
{
int c;
printf("%d\n", c);
}
void bar(void)
{
int b = 50;
}
int main(void)
{
bar();
foo();
}
Output :50
can someone explain the why foo()
print 50 instead of some garbage value?
#include <stdio.h>
void foo(void)
{
int c;
printf("%d\n", c);
}
void bar(void)
{
int b = 50;
}
int main(void)
{
bar();
foo();
}
Output :50
can someone explain the why foo()
print 50 instead of some garbage value?
My GCC compiler generated following warning.
In function ‘bar’:
source_file.c:9:9: warning: unused variable ‘b’ [-Wunused-variable]
int b = 50;
^
source_file.c: In function ‘foo’:
source_file.c:5:5: warning: ‘c’ is used uninitialized in this function [-Wuninitialized]
printf("%d\n", c);
And it's print garbage value. If you use uninitialized variable in C. it is invoked undefined behaviour.
C11 6.3.2.1 (p2):
[...] If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.
This is happening because you didn't intialize the c
variable.
if you try running this:
#include <stdio.h>
void foo(void)
{
int c;
printf("%p\n", &c);
printf("%d\n", c);
}
void bar(void)
{
int b = 50;
printf("%p\n", &b);
}
int main(void)
{
bar();
foo();
}
you'll see that the addresses of the variables are the same. That is why when you print c
it shows 50.
The reason the variable c
uses the same address as b
is because there is no need to keep the value of b
, as b
will never be accessed in foo()
, so if the program allocs another spot in the memory that will be a waste. That is why the variable c
has the same address as b
. And the reason you see 50 (when you print c
), is because you never overwrite the value in that address.
Hope this makes sense.
c
What you have is undefined behavior. That behavior can include printing a correct-looking value. If you want to know why you got a 50 in this case, generate an assembly listing.
Compile with different options or use a different compiler and you'll probably get a different answer.