Procedural Programming with C++
Guess first
Guess: does this C++ code even compile?
Most students get this scope question wrong
Quick check · tap an answer to continue
Lesson notes
Declare and initialise variables of fundamental types and explain how type sets size and range
Key points
- The variable total is declared inside the if block's braces, so its scope ends at that closing brace.
- So the cout after the brace names something that no longer exists, and the compiler rejects it with an undeclared identifier error.
Definitions
- Scope
- Region of code where a name is visible; locals end at their closing brace
Takeaway: Locals vanish at their closing brace.
Quick check: if (x > 0) { int total = 5; } cout << total; What happens?
- Prints 5
- Prints 0
- Compile error
A local variable dies at its closing brace; use it after and it won't compile.
data typeinitialisationscopeScopeCompile error
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