What happens to uninitialized variables? C++

前端 未结 3 1555
北海茫月
北海茫月 2020-11-29 12:58
int main()
{    
    int a;
    cout << a;
    return 0;
}

I am wondering why the value 0 is being output. I thought if a variable is uniniti

3条回答
  •  广开言路
    2020-11-29 13:17

    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.

提交回复
热议问题