Shlomi Shlomi - 1 year ago 163
C++ Question

Unassigned variable value

When I use the code:

#include <iostream>

using namespace std;

int main()

while(1) {
int a;
if(a != 0) {
cout << a << endl;

return 0;

The program never stops.

I learned that unassigned variables store whatever there is in the specific location in memory.
Why always the value of a is 0?

Maybe because its my large memory capacity or its just the compiler?
I use GNU compiler C++ 11
I use Release build configuration.
I'm also newbie to this language.

I use g++ compiler, got my answer.

Answer Source

It depends on the compiler and options. Formally you have an indeterminate value. But the g++ compiler tends to set those variables to 0.

Thinking about what happens at the machine code level, if a is 0 the first time execution passes through the declaration, there is nothing in the program that reasonably could cause the value in that memory location to change, so then you get an infinite loop.

At the source code level, however, use of that indeterminate value (including just checking it) incurs formal Undefined Behavior, where anything or nothing can happen, including that what one expects would happen, happens. :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download