The break statement in C interrupts the execution of the most inner loop or switch. If you use it in a nested structure (loop inside loop or switch inside loop or loop inside switch) it will terminate the inner block.
Advertise on this site. I promise you will like the rates :)
This code will ask us to input numbers and will echo them back to us. When we input 0, the break will stop the execution of the for loop. This example will work the same way with a while or do..while loops.
We use break inside a switch to stop the execution after a particular case. In the next example we want to print the day of the week for a given number (1-Monday, 2-Tuesday…).
If we omit break, the execution of the program will continue with the next case. Sometimes we use this to combine similar cases like in this example we combine the two weekend days:
If we put break in nested constructions, it will interrupt the inner most block. Then the program continues with the next line of code of the outer block. In the next example we nest a switch in a do..while loop. The same rule applies if we nest two loops.
In this case
the break statements will only interrupt the cases. They will not
interrupt the execution of the do..while loop. If we want to use a break
for the loop, we have to write it outside of the switch block.
The keyword break can be used only inside a loop or a switch. It will not stop the execution of a random block of code(for instance an if). This will produce an error. Here is an example of wrong usage:
If you want to stop the execution of a block outside of loop, you can use the goto statement.