Skip to content

Break Continue

Artemis edited this page May 13, 2023 · 2 revisions

C++ Break/Continue

C++ break and continue statements are used to control the flow of a loop. The break statement will stop the loop from executing and the continue statement will skip the current iteration of the loop and move on to the next one.

Break

The break statement is used to exit a loop early. It will stop the loop from executing and continue on with the rest of the program.

The syntax for a break statement is:

break;

For example, consider the following code:

for (int i = 0; i < 10; i++)
{
   if (i == 5)
      break;

   cout << i << endl;
}

This code will print out the numbers 0 to 4, and then exit the loop when it reaches 5.

Continue

The continue statement is used to skip the current iteration of a loop and move on to the next one.

The syntax for a continue statement is:

continue;

For example, consider the following code:

for (int i = 0; i < 10; i++)
{
   if (i % 2 == 0)
      continue;

   cout << i << endl;
}

This code will print out the odd numbers from 1 to 9. When the loop reaches an even number, it will skip it and move on to the next iteration.

Summary

C++ break and continue statements are used to control the flow of a loop. The break statement will stop the loop from executing and the continue statement will skip the current iteration of the loop and move on to the next one.

Clone this wiki locally