break and continue

break and continue

break and continue

In C++, break and continue are control statements that alter the flow of a loop.

The break statement is used to immediately terminate the execution of a loop, and to jump to the statement following the end of the loop. When the break statement is executed inside a loop, the loop is exited regardless of whether the loop condition has been met.

For example, the following code uses a for loop to iterate over the values 1 to 10, but terminates the loop early when the value of i is equal to 5:

				
					for (int i = 1; i <= 10; i++) {

    if (i == 5) {

        break;

    }

    std::cout << i << "";

}
​
				
			

The continue statement, on the other hand, is used to skip the current iteration of a loop and to immediately jump to the next iteration. When the continue statement is executed inside a loop, the remaining statements inside the loop are skipped for the current iteration and the loop continues with the next iteration.

For example, the following code uses a while loop to iterate over the values 1 to 10, but skips over the value of 5:

				
					int i =0;

while (i< 10) {

    i++;

    if (i == 5) {

        continue;

    }

    std::cout << i << "";

}

​
				
			

Both break and continue statements can be used in for, while, and do-while loops to alter the flow of the loop. However, it’s important to use them judiciously to avoid creating code that is hard to read and maintain.

Join To Get Our Newsletter
Spread the love