Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uninitialized variable behaviour in C++

Tags:

People also ask

What is an uninitialized variable in C?

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.

Is uninitialized variables null in C?

In C, variables with static storage duration that are not initialized explicitly are initialized to zero (or null, for pointers).

What value is stored in uninitialized variables in C?

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).

What happens if variable is not initialised?

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)?