C++ Control Flow: if/else, switch, Loops & Jump Statements
Control flow decides which statements run, in what order, and how many times. Every branch, loop and jump in C++ is built from a handful of keywords, and each one has traps the compiler accepts without complaint. All examples below compile and run as written.
What control flow means in C++
Execution moves top to bottom unless a statement changes the path. Three families do that:
- Conditional statements —
if,else,switch— select one path. - Loops —
for,while,do-while, range-basedfor— repeat a block. - Jump statements —
break,continue,return,goto— leave a block early.
| Statement | Purpose | Leaves the block? |
|---|---|---|
if / else if / else | Branch on a condition | No |
cond ? a : b | Choose one of two values | No |
switch / case | Branch on an integral or enum value | No, unless break |
for / while / do-while | Repeat while a condition holds | No |
range-based for | Iterate every element of a range | No |
break | Exit the innermost loop or switch | Yes |
continue | Skip to the next iteration | Yes, one iteration |
goto | Jump to a label in the same function | Yes |
if, else if and else
The condition is converted to bool. Zero means false; every other value means true. Chains are evaluated in order and stop at the first match.
#include <iostream>
int main() {
int score = 82;
if (score >= 90) {
std::cout << "Grade A\n";
} else if (score >= 80) {
std::cout << "Grade B\n";
} else {
std::cout << "Grade C or below\n";
}
}
Grade B
Order the comparisons from most to least restrictive. Writing score >= 80 first would make the 90 branch unreachable.
Braces are not optional in practice
Without braces only the next single statement belongs to the branch:
if (ready)
start();
log(); // runs either way
The dangling else is the classic version of this mistake: an else binds to the nearest unmatched if, not the one the indentation suggests. Always use braces.
The ternary operator
When both branches only produce a value, ?: is shorter and usable inside an expression:
int a = 7, b = 12;
int larger = (a > b) ? a : b;
std::cout << larger << '\n';
12
Do not nest ternaries more than two deep, and do not put side effects in them — readability collapses fast.
switch and case
switch compares one integral or enum expression against constant labels. Without break, control falls through into the next case.
#include <iostream>
int main() {
char op = '*';
int x = 6, y = 7;
switch (op) {
case '+': std::cout << x + y << '\n'; break;
case '-': std::cout << x - y << '\n'; break;
case '*': std::cout << x * y << '\n'; break;
case '/':
if (y != 0) std::cout << x / y << '\n';
else std::cout << "divide by zero\n";
break;
default: std::cout << "unknown operator\n";
}
}
42
Deliberate fallthrough
Grouped labels share one body, which is useful for ranges:
switch (key) {
case 'a': case 'e': case 'i': case 'o': case 'u':
std::cout << "vowel\n";
break;
default:
std::cout << "consonant\n";
}
From C++17, mark intentional fallthrough so compilers stop warning:
switch (level) {
case 1:
unlockBonus();
[[fallthrough]];
case 2:
awardPoints();
break;
}
Declarations inside a case
A declaration under a case label is visible in later cases, so initialise it or wrap the body in braces. C++17 also allows an initialiser in the switch head:
switch (int n = readCount(); n) {
case 0: std::cout << "empty\n"; break;
default: std::cout << n << " items\n";
}
Loops
for
The classic counted loop: initialise, test, then increment. The loop variable is scoped to the loop.
for (int i = 0; i < 5; ++i) {
std::cout << i << ' ';
}
0 1 2 3 4
while
Tests before each iteration. Use it when the trip count is unknown:
int n = 4729, sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
std::cout << sum << '\n';
22
do-while
Tests after the body, so the body always runs at least once. This is the right shape for a menu or any prompt that must appear before the condition can be checked:
int choice;
do {
std::cout << "1) Play 2) Quit\n> ";
std::cin >> choice;
} while (choice != 2);
Range-based for
Iterates each element without an index. Copy with auto, or take a reference to modify in place:
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{3, 8, 15};
for (int x : v) std::cout << x * 2 << ' ';
std::cout << '\n';
for (int& x : v) x *= 2;
for (const int& x : v) std::cout << x << ' ';
}
6 16 30
6 16 30
Use const auto& on non-trivial types to avoid copying every element.
break and continue
break leaves the innermost loop or switch entirely. continue abandons the current iteration and jumps to the loop's next test.
for (int i = 1; i <= 20; ++i) {
if (i % 2 != 0) continue; // skip odd numbers
if (i > 10) break; // stop past 10
std::cout << i << ' ';
}
2 4 6 8 10
Inside a switch nested in a loop, break only leaves the switch. To leave the loop, set a flag, use goto, or move the work into a function and return.
goto and labels
goto jumps within one function. It earns its place mainly for breaking out of deeply nested loops and for single-exit cleanup paths:
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
if (i * j == 4)
goto done;
done:
std::cout << "found\n";
found
You cannot jump over an initialisation into its scope, which is the one rule that catches people out:
goto skip;
int x = 5; // skipped, but still in scope
skip:
std::cout << x; // fine
Infinite loops
for (;;) and while (true) are the idiomatic forms; both are clearer than a constant that happens to be non-zero. Every infinite loop needs an exit, either break, return, or a thrown exception. Server accept loops and game ticks are the normal cases.
Common mistakes
- Assignment in a condition.
if (x = 5)assigns and is always true. C++17'sif (int y = f(); y > 0)makes the intent explicit. - Off-by-one bounds.
i <= sizeon a zero-indexed array reads one element past the end. - Counting down with an unsigned type.
for (unsigned i = 5; i >= 0; --i)never ends, becauseiwraps to a huge value instead of going negative. Usei > 0, or a signed counter. - Semicolon after the condition.
while (x < 10);produces an empty loop body and hangs. - Missing
break. The next case runs too, usually producing wrong arithmetic rather than a compile error. - Floating-point equality.
while (f != 1.0)may never terminate; compare against an epsilon.
Best practices
- Keep loop bodies short enough to read without scrolling.
- Prefer range-based
forwhenever an index is not needed. - Declare loop variables inside the loop so they cannot leak.
- Prefer early
continueover deeply nestedifblocks. - Use
switchfor enums so the compiler warns on unhandled values with-Wswitch. - Reach for
gotoonly when a flag or a function would be worse.
Frequently asked questions
What is the difference between break and continue?
break exits the loop. continue ends only the current iteration and returns to the loop condition.
Can switch work on strings?
Not directly. switch needs an integral or enum type, so compare std::string with if/else chains, or map the string to an enum first.
Is goto bad practice?
No. It is discouraged for ordinary branching, but it is the clearest way out of nested loops and is standard in C cleanup code.
Which loop should I use?
Range-based for for containers, for for a known count, while when the condition can be checked up front, do-while when the body must run at least once.
Written by Krishna Basnet. Last updated 3 November 2026.
All C++ lessons in the Free C++ Course
← Previous: C++ Operators and Expressions | Next: C++ Functions →