In the Loops chapter, every loop ran until its condition became false. Real programs often need more control than that. Sometimes you find what you were looking for halfway through and want to stop immediately. Sometimes one particular item is bad and you just want to skip it and carry on with the rest.
C++ gives you two jump statements for exactly these situations:
break: leave the loop (orswitch) right nowcontinue: skip the rest of this iteration and go to the next one
We will also look at the less famous goto, because it is the honest answer to "how do I break out of two loops at once?", and at the mistakes students commonly make with these statements.
The break Statement
breakimmediately terminates the innermost enclosing loop (for,while,do-while, range-basedfor) orswitchstatement. Execution continues with the first statement after it.
#include <iostream>
int main() {
for (int i = 1; i <= 10; ++i) {
if (i == 4) {
break; // leave the loop immediately
}
std::cout << i << ' ';
}
std::cout << "\nAfter the loop\n";
}
Output:
1 2 3
After the loop
When i becomes 4, break runs. The print statement for 4 is skipped, the update ++i does not run, and the condition is not checked again. Control jumps straight past the closing brace of the loop.
i: 1 → 2 → 3 → 4
↓
break ──→ "After the loop"
Why break Is Useful: Early Exit from a Search
The most common use of break is searching. Once you find the answer, looking at the remaining items is wasted work.
#include <iostream>
int main() {
int position = 0;
int found = -1;
for (int value : {12, 7, 25, 40, 3, 18}) {
++position;
std::cout << "checking " << value << '\n';
if (value > 20) {
found = value;
break; // no need to look at the rest
}
}
if (found != -1)
std::cout << "First value > 20 is " << found
<< " at position " << position << '\n';
}
Output:
checking 12
checking 7
checking 25
First value > 20 is 25 at position 3
Only three of the six values were checked. break works with the range-based for loop exactly as with the classic forms.
Example: Prime Check
To decide if n is prime we try divisors d from 2 while d × d ≤ n. The first divisor we find proves n is not prime, so we stop.
#include <iostream>
int main() {
for (int n : {1, 2, 15, 17, 49, 97}) {
bool isPrime = (n >= 2);
for (int d = 2; d * d <= n; ++d) {
if (n % d == 0) {
isPrime = false;
break; // one divisor is enough
}
}
std::cout << n << (isPrime ? " is prime\n" : " is not prime\n");
}
}
Output:
1 is not prime
2 is prime
15 is not prime
17 is prime
49 is not prime
97 is prime
Why stop at d × d ≤ n? If n = a × b with a ≤ b, then a × a ≤ n, so a divisor (if any) must appear by the time d reaches √n. Together with break, a composite number is usually rejected after just a few checks.
Notice that the break leaves only the inner d loop; the outer loop over the numbers keeps going. More on that below.
break with an Infinite Loop
while (true) plus break is a clean way to write a loop whose exit condition is easiest to test in the middle of the body, such as input validation:
#include <iostream>
int main() {
int n;
while (true) {
std::cout << "Enter a positive number: ";
if (!(std::cin >> n)) {
std::cout << "\nNo more input\n";
break;
}
if (n > 0) {
break; // valid: leave the loop
}
std::cout << n << " is not positive, try again\n";
}
std::cout << "You entered " << n << '\n';
}
Input: -4 0 25
Output:
Enter a positive number: -4 is not positive, try again
Enter a positive number: 0 is not positive, try again
Enter a positive number: You entered 25
(When you type the input interactively, each number appears on its own line after the prompt; here the input came from a file, so it is not echoed.) The first break handles the case where input runs out (or is not a number), so the loop can never get stuck waiting for input that will never arrive.
The continue Statement
continueskips the remaining statements of the current iteration of the innermost enclosing loop and moves on to the next iteration. It cannot be used in aswitchon its own, only inside a loop.
#include <iostream>
int main() {
for (int i = 1; i <= 10; ++i) {
if (i % 3 == 0) {
continue; // skip multiples of 3
}
std::cout << i << ' ';
}
std::cout << '\n';
}
Output:
1 2 4 5 7 8 10
Where Exactly Does continue Jump To?
This is the detail that matters most, and it differs between loop types:
Loop | After |
|---|---|
| the update expression (e.g. |
| the condition directly |
| the condition at the bottom |
range-based | the next element of the range |
In a for loop the update is never skipped, which is why continue is so safe there. In a while loop, the update is just an ordinary statement in the body, so continue can skip it. Look at this buggy loop:
int i = 0;
while (i < 6) {
if (i == 3) {
continue; // BUG: jumps to the condition, ++i never runs
}
std::cout << i << ' ';
++i;
}
This loop handles 0, 1 and 2 and then never finishes: once i is 3, every iteration hits continue before reaching ++i, so i stays 3 forever. The fix is to update first:
#include <iostream>
int main() {
int i = 0;
while (i < 6) {
++i; // update FIRST, so continue cannot skip it
if (i == 3) {
continue;
}
std::cout << i << ' ';
}
std::cout << '\n';
}
Output:
1 2 4 5 6
In a do-while, continue jumps to the condition at the bottom, not to the top of the body. The condition is still checked:
#include <iostream>
int main() {
int i = 0;
do {
++i;
if (i % 2 == 0) {
continue; // jumps to the condition check below
}
std::cout << i << ' ';
} while (i < 7);
std::cout << '\n';
}
Output:
1 3 5 7
Why continue Is Useful: Filtering Bad Data
continue lets you deal with the "skip" cases at the top of the loop, so the main logic below is not buried inside an extra if:
#include <iostream>
int main() {
int sum = 0, skipped = 0;
for (int x : {5, -2, 8, -7, 10}) {
if (x < 0) {
++skipped;
continue; // ignore negative readings
}
sum += x;
}
std::cout << "Sum of positives = " << sum
<< ", skipped = " << skipped << '\n';
}
Output:
Sum of positives = 23, skipped = 2
This style is called a guard clause: handle the special case and get out of the way early.
break vs continue
Feature |
|
|
|---|---|---|
Effect | Ends the whole loop | Ends only the current iteration |
Next statement executed | First statement after the loop | Update ( |
Allowed in | Yes (ends the | Only if the |
Affects nested loops | Only the innermost one | Only the innermost one |
Typical use | Search found, error, user quit | Skip invalid or uninteresting items |
break= "I'm done with this loop."continue= "I'm done with this item."
break and continue in Nested Loops
Both statements affect only the innermost loop that contains them. They never reach "through" to an outer loop.
#include <iostream>
int main() {
for (int i = 1; i <= 3; ++i) {
for (int j = 1; j <= 3; ++j) {
if (j == 2) {
break; // leaves ONLY the inner loop
}
std::cout << "(" << i << "," << j << ") ";
}
std::cout << "| end of row " << i << '\n';
}
}
Output:
(1,1) | end of row 1
(2,1) | end of row 2
(3,1) | end of row 3
The outer loop ran all three times. Each inner loop was cut short at j == 2.
Unlike Java, C++ has no labelled break (break outer; does not exist). So how do you leave two loops at once? There are three common ways.
Way 1: A Flag Variable
#include <iostream>
int main() {
int target = 10;
bool found = false;
int a = 0, b = 0;
for (int i = 1; i <= 9 && !found; ++i) {
for (int j = i; j <= 9; ++j) {
if (i * j == target) {
a = i;
b = j;
found = true;
break; // leaves inner loop; outer stops via !found
}
}
}
if (found)
std::cout << a << " x " << b << " = " << target << '\n';
}
Output:
2 x 5 = 10
The inner break ends the inner loop, and the outer condition !found ends the outer loop. Simple and very readable, but you must remember to check the flag in every outer loop.
Way 2: goto
goto label; jumps to a statement marked label: in the same function. It has a bad reputation because jumping around freely makes code hard to follow ("spaghetti code"), but jumping forward and out of nested loops is the one use many style guides accept.
#include <iostream>
int main() {
int target = 12;
for (int i = 1; i <= 9; ++i) {
for (int j = i; j <= 9; ++j) {
if (i * j == target) {
std::cout << i << " x " << j << " = " << target << '\n';
goto done; // jumps out of both loops at once
}
}
}
std::cout << "not found\n";
done:
std::cout << "search over\n";
}
Output:
2 x 6 = 12
search over
Note that 1 × 12 is not found because j only goes up to 9. Rules to know about goto:
The label must be in the same function.
You may not jump forward past the declaration of an initialized variable into its scope (g++ reports "jump to label" with a note that it "crosses initialization" of that variable).
Jumping out of a block is fine; local objects of the blocks you leave are destroyed properly.
Way 3: Put the Loops in a Function and return
Once you have learned Functions (the very next chapter), this is usually the cleanest choice: move the nested loops into their own function and return the moment you find the answer. return leaves every loop in the function at once, and the function name documents what the search does.
A Classic Trap: break Inside a switch Inside a Loop
From the Switch Statement chapter you know that break ends a switch. When the switch is itself inside a loop, break belongs to the switch (the innermost one), not to the loop:
#include <iostream>
int main() {
int balance = 100;
for (char cmd : {'d', 'w', 'q', 'd'}) {
switch (cmd) {
case 'd':
balance += 50;
std::cout << "deposit -> " << balance << '\n';
break;
case 'w':
balance -= 30;
std::cout << "withdraw -> " << balance << '\n';
break;
case 'q':
std::cout << "quit requested\n";
break; // exits the switch, NOT the loop!
}
}
std::cout << "Final balance: " << balance << '\n';
}
Output:
deposit -> 150
withdraw -> 120
quit requested
deposit -> 170
Final balance: 170
The user asked to quit, yet the last deposit was still processed. Fix it with a flag and a second break placed outside the switch:
#include <iostream>
int main() {
int balance = 100;
bool running = true;
for (char cmd : {'d', 'w', 'q', 'd'}) {
switch (cmd) {
case 'd': balance += 50; break;
case 'w': balance -= 30; break;
case 'q': running = false; break;
}
if (!running) {
break; // this break belongs to the for loop
}
}
std::cout << "Final balance: " << balance << '\n';
}
Output:
Final balance: 120
Interestingly, continue inside a switch that sits in a loop does go to the loop, because continue only cares about loops. Mixing the two in one switch confuses readers, so use this sparingly.
Common Mistakes
Using
breakoutside a loop or switch. Abreakinside a plainifthat is not in a loop is a compile error ("break statement not within loop or switch").breakleaves loops and switches, never anif.Expecting
breakto leave all nested loops. It leaves only the innermost one. Use a flag,goto, or a function withreturn.continueskipping the update in awhileloop, producing an infinite loop. Update before thecontinue, or use aforloop.Forgetting that
breakin aswitchbelongs to the switch when the switch is inside a loop.Overusing them. Five
breaks andcontinues scattered through one long loop make it hard to see when the loop ends. If the exit condition fits naturally in the loop header, put it there.
Interview and GATE Questions
Q1. What is the output?
int count = 0;
for (int i = 0; i < 10; ++i) {
if (i % 2 == 0) continue;
if (i > 6) break;
++count;
}
std::cout << count;
int count = 0;
for (int i = 0; i < 10; ++i) {
if (i % 2 == 0) continue;
if (i > 6) break;
++count;
}
std::cout << count;
3. Even values are skipped. Odd values 1, 3 and 5 increment count. At i = 7, 7 > 6 triggers break.
Q2. In a for loop, does continue skip the increment expression?
for loop, does continue skip the increment expression?No. In a for loop, continue transfers control to the end of the loop body, after which the update expression runs and then the condition is checked. In a while or do-while loop there is no separate update part, so any increment written after the continue in the body is skipped.
Q3. How many times is "Hi" printed?
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j) {
if (j == i) break;
std::cout << "Hi\n";
}
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j) {
if (j == i) break;
std::cout << "Hi\n";
}
3 times. For i = 0: breaks at j = 0, prints 0. For i = 1: prints at j = 0, breaks at j = 1 → 1. For i = 2: prints at j = 0, 1 → 2. Total 0 + 1 + 2 = 3.
Q4. Does C++ support labelled break like Java's break outer;?
break outer;?No. Standard C++ (up to C++23) has no labelled break or continue. Use a flag variable, goto to a label after the loops, or move the loops into a function and return. (A proposal to add labelled loops exists for a future standard, but you cannot use it in C++23.)
Q5. Can continue appear inside a switch?
continue appear inside a switch?Only if that switch is inside a loop. Then continue moves to the next iteration of the enclosing loop. A continue in a switch that is not inside any loop is a compile error.
Summary
breakterminates the innermost loop orswitch; execution resumes after it.continueends the current iteration; inforit goes to the update, inwhile/do-whileto the condition.Both affect only the innermost loop. C++ has no labelled break: use a flag,
goto, or a function withreturn.A
breakinside aswitchleaves the switch, not the surrounding loop.In
whileloops, make surecontinuecannot skip the update.Use
breakfor early exit (search, quit, error) andcontinuefor guard clauses that skip unwanted items.
breakleaves the loop;continueleaves the iteration. Both only ever leave the innermost one.