Control Flow in C++
Master control flow in C++ - conditionals, switch statements, loops, and loop control with practical Docker-ready examples
Control flow determines the order in which statements execute. Instead of running top to bottom every time, your program can branch on conditions, repeat work, and skip or stop iterations. These constructs turn a list of instructions into actual logic.
As a multi-paradigm language with deep C roots, C++ inherits the familiar structured control flow of if/else, switch, and the three loop forms (for, while, do-while). On top of that foundation, modern C++ adds quality-of-life features: the range-based for loop (C++11) for iterating containers, and if/switch statements with initializers (C++17) that scope a variable to the branch where it’s used.
In this tutorial you’ll learn how to make decisions with conditionals and the ternary operator, branch on discrete values with switch, repeat work with each loop type, and steer iterations with break and continue. Every example compiles cleanly with g++ and runs in the official gcc:14 Docker image.
Conditionals: if, else if, else
The if statement runs a block only when its condition is true. Chain else if for additional cases and else for a fallback. C++ also offers the ternary operator ?: for compact expressions and, since C++17, an init-statement that scopes a variable to the if.
Create a file named conditionals.cpp:
| |
The init-statement form (if (init; condition)) keeps short-lived variables out of the surrounding scope, which prevents accidental reuse and keeps code tidy.
Switch Statements
When you’re branching on a single integer or character value with many discrete cases, switch is clearer than a long if/else if chain. Each case needs a break to stop execution from “falling through” into the next case — but deliberate fall-through is also useful for grouping cases that share behavior.
Create a file named switch_statement.cpp:
| |
The default case handles any value not matched by a case label. Because 'A', 'B', and 'C' have no break between them, they all flow into the same std::cout statement.
Loops: for, while, and do-while
C++ provides three loop forms. The classic for loop bundles initialization, condition, and update in one line. The while loop checks its condition before each iteration. The do-while loop checks after, so its body always runs at least once. C++11 added the range-based for loop for clean iteration over containers.
Create a file named loops.cpp:
| |
Using const auto& in the range-based loop avoids copying each element and signals that the loop won’t modify the container — the idiomatic choice for read-only iteration.
Loop Control: break and continue
Two keywords steer execution inside loops. break exits the enclosing loop immediately. continue skips the rest of the current iteration and jumps to the next one.
Create a file named loop_control.cpp:
| |
Running with Docker
Each example is a standalone program. Compile and run them with the official gcc:14 image — no local toolchain required.
| |
To use a specific standard (the init-statement and range-based examples need C++11 or later, which is the gcc:14 default), add the -std flag, for example g++ -std=c++17 -o conditionals conditionals.cpp.
Expected Output
Running conditionals:
Grade: B
7 is odd
Allowed to drive
Score ends in 5 (remainder 5)
Running switch_statement:
Wednesday
Passing grade
Running loops:
Counting up: 1 2 3 4 5
T-minus 3
T-minus 2
T-minus 1
Runs once even though n == 0
Language: C++
Language: Rust
Language: Go
Running loop_control:
Searching for 4:
Checking 1
Checking 2
Checking 3
Found 4, stopping
Odd numbers from 1 to 7: 1 3 5 7
Key Concepts
if/else if/elseevaluate conditions top to bottom; the first true branch runs and the rest are skipped.- Ternary operator
?:is an expression, not a statement — it returns a value, making it ideal for compact assignments. switchbranches on integral or character values; rememberbreakto prevent unintended fall-through, but use intentional fall-through to group cases that share an action.- Three loop forms:
forfor counted iteration,whilefor pre-checked loops, anddo-whilewhen the body must run at least once. - Range-based
for(C++11) iterates containers cleanly; preferconst auto&for read-only access to avoid copies. - Init-statements in
ifandswitch(C++17) scope a variable to the branch, keeping the surrounding scope clean. breakexits the enclosing loop entirely, whilecontinueskips to the next iteration — both apply to the innermost loop only.- Truthiness: any non-zero numeric or non-null pointer value is treated as
truein a condition, a behavior C++ inherits from C.
Comments
Loading comments...
Leave a Comment