This question already has answers here:
Closed 4 years ago.
I am newbie to the C programming.I know this is a very simple question but I need some advice.
I am exercising with the control structure if statement
. I came across one example
Here is the code:-
#include<stdio.h>
int main()
{
int a = 200, b, c ;
if (a >= 300)
{
b = 100 ;
c = 200 ;
}
printf ( "b=%d\nc=%d", b, c ) ;
return 0;
}
And the output of this is :-
b=32767
c=0
Here i am expecting the output as the both value to be zero. By seeing this output i am little surprised that why the garbage value in the variable b
.
What is the reason behind that?Or I am declaring the variable in wrong way. what should the whole scenario behind this?
In case
if (a >= 300)
fails, b
and c
will not be assigned any values.
Now, b
and c
being automatic local variables, unless initialized explicitly, they contain indeterminate values.
Referring C11
, chapter §6.7.9, Initialization
If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate.[...]
Using unitialized local variables to access their values invoke undefined behavior.
Referring Annex §J.2 of the same standard, for Undefined behavior
The value of an object with automatic storage duration is used while it is
indeterminate.
So, it's always advisable to initialize your local variables, like
int a = 200, b = 0, c = 0;
That said, FWIW, int main()
should be int main(void)
at least to conform to the standard.
It seems like you assume declaring a variable implicitly sets it's value to 0.
Declaring a variable but not initializing is a great place for undefined behaviors.
Once you declare a variable, it gets memory allocated to it on the stack, but nothing is done to that memory space, so it can hold the data remains of previous calls, or just garbage data on the stack space.
It's called undefined behavior because that data can incidentally be the actual data you expect, but it can (and probably will) be something else entirely. this is a non-deterministic behavior.
What you need to do is initialize the values first, to make sure your run is deterministic.
You have to initialize your variables to 0:
#include<stdio.h>
int main()
{
int a = 200, b = 0, c = 0;
if (a >= 300)
{
b = 100 ;
c = 200 ;
}
printf ( "b=%d\nc=%d", b, c ) ;
return 0;
}
In C and C++ your declaration does not initialize your int variables to 0. Any declaration ends up with random values inside the variable...