c++variablesinitialization

What happens to uninitialized variables? C++


int main()
{    
    int a;
    cout << a;
    return 0;
}

I am wondering why the value 0 is being output. I thought if a variable is uninitialized, it would output a garbage value.

However, I also remember hearing that the default value of an integer is 0 so I am a bit confused.


Solution

  • The default behavior of an uninitialized function scope (i.e., local) integer in C++ is for it to be indeterminate, which is fine; however if that value is used before it is defined it introduces undefined behavior, and anything could happen - demons could fly out of your nose.

    This page on cppreference provides examples of default integer behavior.

    On the other hand, all non-local, thread-local variables, not just integers, are zero initialized. But this case wasn't included in your original example.

    (Side note: It is generally considered good practice to simply initialize variables anyway and avoid potential hazards altogether... Especially in the form of global variables. )

    There are exceptions to best practice using global variables in rare special cases, such as some embedded systems; which initialize values based off of sensor readings on startup, or during their initial loop iteration... And need to retain a value after the scope of their loop ends.