Default Values: A Tale of Two Variables
In C , uninitialized variables pose a conundrum. Conventional wisdom dictates that such variables should hold garbage values. However, in a puzzling scenario, the following code outputs 0:
int main() { int a; cout << a; return 0; }
Why does this code behave unexpectedly?
The explanation lies in the distinct behavior of local and non-local variables. For local variables like "a" in the given code, C assigns them indeterminate values by default. Using these values without initialization triggers undefined behavior, whose consequences can range from the innocuous to the catastrophic.
Alternatively, non-local variables, including thread-local variables, inherit a zero initialization from their global counterparts. However, in the provided example, "a" is a local variable, not subject to this initialization.
To avoid pitfalls, programmers are strongly encouraged to explicitly initialize all variables. Global variables, while occasionally justified in certain niche applications, should be approached with caution due to their potential for undefined behavior.
The above is the detailed content of Why Does an Uninitialized Local Variable in C Print 0?. For more information, please follow other related articles on the PHP Chinese website!