Program flow in control loops can be manipulated using break, return, continue. Whilst their similar in that they end the current iteration, they each have some slight nuances.
One program, three exits
Consider the program below:
#include <iostream>
#include <string>
void prepareDinner() {
std::string input;
std::cout << "--- Starting dinner preparation ---\n";
while (true) {
std::cout << "\nAction (chop / wipe / spoil): ";
std::getline(std::cin, input);
if (input == "wipe") {
std::cout << "Wiped a spill.\n";
continue; // skip the rest of this iteration
}
if (input == "spoil") {
std::cout << "The meat is spoiled. Kitchen closed.\\n";
return; // abandon the function
}
if (input == "chop") {
std::cout << "Vegetables chopped.\n";
break; // leave the loop, finish the recipe
}
// This line is only reached for inputs that aren't handled above.
std::cout << "Unknown action. Try again.\\n";
}
std::cout << "Sizzling vegetables. Dinner is served.\n";
}
int main() {
prepareDinner();
}
- First exit
If we choose to chop the meat, once the program reaches the break, it exits the while loop, thus Still chopping ingredients isn’t printed.
Dinner is served!
--- Starting dinner preparation ---
Action (chop / wipe / spoil): chop
Vegetables chopped.
Sizzling vegetables. Dinner is served.
2. Second exit
If we choose wipe, the program skips the current iteration of the loop. Subsequent if‘s below it are skipped and program execution jumps straight to the top.
--- Starting dinner preparation ---
Action (chop / wipe / spoil): wipe
Wiped a spill.
Action (chop / wipe / spoil):
3. Third exit
If we choose to spoil the meat since we’re evil, the program reaches a return. It exits the if statement, while loop AND prepareDinner(). Thus, return can be used to exit out of a nested loop.
--- Starting dinner preparation ---
Action (chop / wipe / spoil): spoil
The meat is spoiled. Kitchen closed.
break will exits the current loop whilst return exits the function in which it is called. The later is more powerful.
When to use which?
- Use
continuewhen the current iteration has nothing left to do, but the loop should keep running. Skip this case, try the next one. - Use
breakwhen the work the loop was doing is finished or impossible to finish. Stop iterating; we’re done here. - Use
returnwhen there is nothing more for the function to do at all. Walk away from the entire computation
In Conclusion
Program flow can be altered in 3 ways.
continueto abandon the current iterationbreakto end the loopreturnto leave the function.