Why is reading an uninitialized variable undefined behavior?
Short answer
An uninitialized local variable holds an indeterminate value; reading it is UB because its bits are arbitrary and, for some types, may not even be a valid value. The program may appear to work by luck, then fail unpredictably.
Advertisement
AModel answer
An uninitialized local variable holds an indeterminate value; reading it is UB because its bits are arbitrary and, for some types, may not even be a valid value. The program may appear to work by luck, then fail unpredictably. Always initialize variables (e.g., int x = 0; or brace-init) before use.
int x;
if (x > 0) { /* UB: x is uninitialized */ }Real-world example
An uninitialized flag intermittently enables a code path, causing a bug that only appears on some runs.
Likely follow-ups
- How do you avoid it? | Why can it appear to work?
Related topics