Control Flow¶
Control flow statements determine the execution path of your code. In Modern C++, control flow constructs have been enhanced to be more expressive, scope-safe, and highly optimization-friendly.
1. Conditional Statements¶
The if / else Statement¶
The basic if statement evaluates a boolean expression and executes a block if true.
C++17 Init-Statements for if¶
C++17 introduced the ability to declare and initialize variables directly within the scope of the if statement. This keeps the variable local to the branch, preventing it from polluting the surrounding scope.
2. The switch Statement¶
The switch statement selects one of many code blocks to execute based on an integral or enumeration expression.
Fallthrough and [[fallthrough]] Attribute¶
By default, if a case block does not end with a break or return, the compiler continues executing the code in the next case block. This is called "fallthrough."
In C++17, if you intentionally want fallthrough behavior, you should mark it with the [[fallthrough]]; attribute to silence compiler warnings:
3. Compile-Time Conditionals: if constexpr (C++17)¶
One of the most powerful features of Modern C++ is if constexpr. It allows conditional execution at compile time. The compiler evaluates the condition, keeps the branch that evaluates to true, and discards the false branch completely from the generated binary.
This is widely used in generic template programming to run different code depending on type properties.
If we wrote a standard if here, compiling process_input(num) would fail because the compiler would try to compile *value (dereferencing a non-pointer integer num). if constexpr prevents the inactive branch from being compiled.
4. Loops and Iterations¶
while and do-while Loops¶
whileloops check the condition before executing the block.do-whileloops check the condition after executing the block, ensuring the body runs at least once.
Traditional for Loop¶
Ideal when you need to know the index or loop counter.
Range-Based for Loop¶
Introduced in C++11, this is the modern way to iterate through containers (like std::vector, std::array, and strings). It is cleaner and prevents off-by-one boundary errors.
C++20 Range Loop with Init-statement¶
Similar to C++17 if statements, C++20 allows you to declare variables inside a range-based for loop, useful for maintaining an index counter:
5. Jump Statements: break and continue¶
break: Exits the nearest enclosing loop orswitchblock immediately.continue: Skips the remaining lines in the current iteration of a loop and moves directly to the next loop evaluation.
Related Guides¶
- Functions — How code organization interacts with control flow.
- Operators — Comparison operations and short-circuit evaluation rules.