Procedural Programming with C++
Explainer
Why Your Counter Starts at 32767
In C++, a local int you never set can hold any random number.
Quick check · tap an answer to continue
Lesson notes
Key points
- A local variable declared like int total; gets memory on the stack but no starting value.
- Reading that variable before assigning it is undefined behaviour, so results can change between runs or compilers.
- Global and static variables are different: C++ zero-initializes them automatically before main runs.
- So always initialize accumulators like sum or count, and compile with warnings such as -Wall to catch mistakes.
Definitions
- Uninitialized variable
- A variable declared without a value; reading it gives whatever bits were left in that memory.
Takeaway: Initialize every local variable when you declare it.
Quick check: What does a local int x; hold before assignment?
- Always 0
- An unpredictable value
- A compile error
DeclarationUndefined behaviourZero-initializationInitialize always
Lessons like this, for your syllabus.
Short narrated study videos written for your course, level and exam. Free to start.
Get lessons for your own syllabus