What happens to uninitialized variables? C++

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.

Leave a Comment