An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using. This can lead to errors that are very hard to detect since the variable's value is effectively random, different values cause different errors or none at all.
In C, variables with static storage duration that are not initialized explicitly are initialized to zero (or null, for pointers).
The value in an uninitialized variable is one of: zero, a compiler dependent value (such as 0xCC's in visual studio), or data previously stored in that memory location (old data).
Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.
I've checked myself, I wrote a program like this
int main() {
int i;
cout << i;
return 0;
}
I ran the program a few times and the result was same all the time, zero. I've tried it in C and the result was the same.
But my textbook says
If you don’t initialize an variable that’s defined inside a function, the variable value remain undefined.That means the element takes on whatever value previously resided at that location in memory.
How's this possible when the program always assign a free memory location to a variable? How could it be something other than zero(I assume that default free memory value is zero)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With