Statements#
Key statement syntax and critical caveats based on C++ Primer, 5th ed. Chapter 5 (Statements).
1. The if Statement and Dangling Else#
In C++, an else branch is syntactically paired with the closest preceding unmatched if.
if (condition1)
if (condition2)
DoSomething();
else // Warning: pairs with condition2's if, not condition1!
DoAnother();To eliminate ambiguity and prevent logical bugs, always use explicit curly braces ({}) to wrap compound statement blocks.
2. The switch Statement and Bypassing Variable Initialization#
The curly braces { ... } wrapping the body of a switch statement form a single scope. A case label is merely a jump target and does not establish a separate nested scope.
Consequently, any variable declared after one case label remains in scope for all subsequent case branches.
Why Bypassing Initialization is a Compile Error#
Jumping across a case label past a variable definition that has an explicit initializer (= val) or an implicit default constructor is a compile-time error.
switch (val) {
case 1:
// string s; // ❌ Compile error: default constructor execution is bypassed
// int ix = 42; // ❌ Compile error: explicit initialization (= 42) is bypassed
int iy; // ⭕ Valid: primitive variable without initializer can be defined
break;
case 2:
// If execution jumped directly to case 2:
iy = 0; // ⭕ Valid: iy is in scope
// s.empty(); // If s were allowed, this would access an unconstructed object with corrupt memory
break;
}- Primitive Types (
int iy;): Without an initializer, this only allocates uninitialized stack storage. The compiler allows it, andiyis in scope and accessible incase 2. - Class Objects (
string s;) and Explicit Initializers (int ix = 42;): Objects require their constructor or initializer code to run. Jumping directly tocase 2skips this initialization, leaving an unconstructed object in scope. Accessing such an object leads to severe runtime crashes; hence, the compiler prohibits jumping over initializations.
Solution (Explicit Block Scope): If a variable must be defined inside a
case, wrap thatcasein curly braces{ ... }to confine the variable’s scope.case 1: { string s = "hello"; // ⭕ Valid: s is scoped strictly inside this block break; } case 2: // s is out of scope here break;
3. C++11 Range for Statement#
Used to iterate through all elements of a container or array.
vector<int> v = {0, 1, 2, 3, 4};
for (auto &r : v) {
r *= 2;
}Compiler Expansion#
The compiler transforms a range for loop into an equivalent iterator-based traditional loop:
for (auto beg = v.begin(), end = v.end(); beg != end; ++beg) {
auto &r = *beg;
r *= 2;
}Important Caveat: Do Not Modify Container Size During Traversal#
- As shown in the expansion above, the
end()iterator is evaluated and cached inendonce at loop entry. - Modifying the size of the container (e.g., calling
v.push_back()orv.erase()) inside the loop can invalidate iterators or cause the cachedendto become out-of-date, leading to undefined behavior. - Therefore, never add or remove elements from a container inside a range
forloop.
4. try Blocks and Exception Handling#
C++ exception handling consists of throw, try, and catch.
try {
if (val < 0) {
throw runtime_error("Negative value not allowed");
}
} catch (const runtime_error &err) {
cerr << err.what() << '\n';
} catch (...) {
// Universal catch-all handler
}Handler Search and Stack Unwinding#
- When a
throwexecutes, execution of the current block immediately halts, and the runtime searches for a matchingcatchhandler associated with the currenttryblock. - If no matching handler is found in the current function, the exception propagates up to the caller function.
- As execution unwinds up the call stack, destructors for all local objects in exited scopes are automatically invoked (this process is called Stack Unwinding).
Uncaught Exceptions and Program Abort#
- If the exception propagates all the way up through
main()without finding a matchingcatchhandler, it becomes an uncaught exception. - When an uncaught exception occurs, the C++ runtime calls the standard library function
std::terminate(). - By default,
std::terminate()invokesabort(), immediately terminating the program abnormally.