Reputation: 95
#include <stdio.h>
int main()
{
int i,j=3;
i=4+2*j/i-1;
printf("%d",i);
return 0;
}
It will print 9 every time,though i is not initialized, So, it must print any garbage value. Please Explain...
Upvotes: 0
Views: 7103
Reputation: 29213
The value of an uninitialized local variable in C is indeterminate and reading it can invoke undefined behavior.
Now, repeatedly executing a particular program compiled with a particular compiler in a particular environment (as you are doing) is likely to yield the same (still undefined, of course) behavior. This could be because the OS will usually give your process the same range of logical memory every time you run it and thus the garbage that your program reads has a good chance of being the same every time (but it's still garbage, nonetheless). Or it could be because the compiler doesn't even bother to give you a binary representation of the garbage you would be reading and instead gives you something else (as long as it doesn't violate the standard).
Upvotes: 10
Reputation: 105992
When a variable is used before its initialization, it would take a garbage value from memory.
A Garbage value is a value last stored in a memory location reserved for that variable (in this case i
).
When you compile your program, every time it will fetch that previous stored value from that memory location and will result in an undefined behavior.
It is not necessary it will give the output 9
every time. The program may behave differently when compiled with different compilers.
Upvotes: 1
Reputation: 239443
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf is the International Standard for C Programming languages
Page No : 126
Heading : Semantics
Item No : 10
Quoting from that
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
This must answer your question.
EDIT : Suggested by @Jens Gustedt in the comments
6.3.2.1, p2, says 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.
Upvotes: 2
Reputation: 4268
Your code will result in Undefined Behavior
. Undefined behavior refers to computer code whose behavior is unpredictable. The output of the code depends on the compiler, environment.
Upvotes: 2