Possible Duplicate:
Default values of int when not initialized in c. why do i get different outputs?
Beginner so be lil soft..am compiling a simple code below, I am not assigning any value to my variables but C program generates some random values, why is it so?(Only 2nd variable generates random integers)
So where these values came from?
#include<stdio.h>
main(void) {
int var1;
int var2;
printf("Var1 is %d and Var2 is %d.", var1, var2);
return 0; //Book says I should use this for getting an output but my compiler anyways compile and return me values whether I use it or not
}
//Output 1st compiled: var1 = 19125, var2 = 8983
//Output 2nd compiled: var1 = 19125, var2 = 9207
//Output 2nd compiled: var1 = 19125, var2 = 9127
Your C program is compiled to some executable program. Notice that if you compile on Linux using
gcc -Wall, you’ll get warnings about uninitialized variables.The
var1andvar2variables get compiled into using some stack slots, or some registers. These contain some apparently random number, which your program prints. (that number is not really random, it is just unpredictable garbage).The C language does not mandate the implicit initialization of variables (in contrast with e.g. Java).
In practice, in C I strongly suggest to always explicitly initialize local variables (often, the compiler may be smart enough to even avoid emitting useless initialization).
What you observe is called undefined behavior.
You’ll probably observe a different output for
var1if you compiled with a different compiler, or with different optimization flags, or with a different environment (probably typingexport SOMEVAR=somethingbefore running again your program could change the output forvar1, or running your program with a lot of program arguments, etc…).You could (on Linux) compile with
gcc -fverbose-asm -Sand add various optimization flags (e.g.-O1or-O2…) your source codeyoursource.cand look inside the generatedyoursource.sassembler code with some editor.