C code :
int a;
printf(\"\\n\\t %d\",a); // It\'ll print some garbage value;
So how does these garbage values are assigne
Does it mean C first allocates memory to variable 'a' and then what ever there is at that memory location becomes value of 'a'? or something else?
Correct. It is worth mentioning that the "allocation" of automatic variables such as int a
is virtually nonexistent, since those variables are stored on the stack or in a CPU register. For variables stored on the stack, "allocation" is performed when the function is called, and boils down to an instruction that moves the stack pointer by a fixed offset calculated at compile time (the combined storage of all local variables used by the function, rounded to proper alignment).
The initial value of variables assigned to CPU registers is the previous contents of the register. Because of this difference (register vs. memory) it sometimes happens that programs that worked correctly when compiled without optimization start breaking when compiled with optimization turned on. The uninitialized variables, previously pointing to the location that happened to be zero-initialized, now contain values from previous uses of the same register.
int a
;
While declaring a variable, the memory is allocated. But this variable is not assigned which means the variable a
is not initialized. If this variable a
is only declared but no longer used in the program is called garbage value.
For example:
int a, b;
b=10;
printf("%d",b);
return 0;
Here it's only declared but no longer assigned or initialized. So this is called garbage value.
Initially memory is having some values, those are unknown values, also called garbage values, when ever we declare a variable some memory was reserved for the variable according to datatype we specified while declaring, so the memory initial value is unknown value, if we initialize some other value then our value will be in that memory location.
Does it mean C first allocates memory to variable 'a' and then what ever there is at that memory location becomes value of 'a'?
Exactly!
Basically, C doesn't do anything you don't tell it to. That's both its strength and its weakness.