Control Flow in C++ (continue, break, return)
Video Reference: Control Flow in C++ by The Cherno
Full Playlist: C++ Programming Tutorials
1. continue Statement
Purpose: Skip to the next iteration of a loop.
Timestamp Reference: 00:02:34
Example: Skip Even Numbers
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) { // Skip even indices
continue;
}
std::cout << "Hello World (i=" << i << ")\n";
}
Output:
Hello World (i=1)
Hello World (i=3)
- When
iis even,continueskips printing and jumps toi++.
2. break Statement
Purpose: Exit the loop immediately.
Timestamp Reference: 00:04:07
Example: Exit Loop Early
for (int i = 0; i < 5; i++) {
if (i > 2) {
break; // Exit loop when i exceeds 2
}
std::cout << "Hello World (i=" << i << ")\n";
}
Output:
Hello World (i=0)
Hello World (i=1)
Hello World (i=2)
- Loop terminates at
i=3.
3. return Statement
Purpose: Exit the current function.
Timestamp Reference: 00:05:49
Example: Early Exit from main()
int main() {
for (int i = 0; i < 5; i++) {
if (i > 3) {
return 0; // Exit program when i > 3
}
std::cout << "Hello World (i=" << i << ")\n";
}
std::cin.get();
}
Output:
Hello World (i=0)
Hello World (i=1)
Hello World (i=2)
Hello World (i=3)
- Program exits before printing
i=4.
Key Differences
| Statement | Scope | Behavior |
|———–|———————|———————————–|
| continue| Inside loops | Skips to next iteration |
| break | Loops/switch | Exits current loop/switch |
| return | Any function | Exits function (returns a value) |
Common Pitfalls
returninmain(): Must return an integer (e.g.,return 0).- Dead Code:
return 0; // Code below this line never executes std::cout << "This will never print!"; continuePlacement:- Useless if placed at the end of a loop (e.g.,
for(...) { ... continue; }).
- Useless if placed at the end of a loop (e.g.,
Need a Visual Demo?
Revisit specific sections:
