Control Flow¶
Control flow statements allow your program to make decisions and repeat actions. Modern C++ introduces powerful features to make these safer and more expressive.
Conditional Statements¶
if and else¶
The standard if statement works as expected. C++17 introduced init-statements for if, allowing you to limit the scope of variables.
switch Statement¶
Useful for checking a variable against multiple constant values.
Fallthrough: If you omit break, execution continues to the next case. In C++17, use [[fallthrough]]; to indicate this is intentional.
if constexpr (C++17)¶
This is a compile-time conditional. The "false" branch is discarded during compilation. It is essential for template programming.
Loops¶
while and do-while¶
while: Checks condition before the loop body.do-while: Checks condition after the loop body (guaranteed to run at least once).
Standard for Loop¶
The classic C-style loop.
Range-based for Loop (Modern C++)¶
This is the preferred way to iterate over arrays, vectors, and other containers. It eliminates off-by-one errors.
Jump Statements¶
break: Exits the nearest loop or switch.continue: Skips the rest of the current iteration and starts the next one.return: Exits the function.