At least in C you shouldn't use break
and / or continue
βmost of the timeβ (as your question says what you did) to control the flow of your loops. The loop condition should indicate under what circumstances the loop should stop; someone supporting your code should not dig up the code in the body of your loop to find out what causes break
, which causes the loop to stop.
For example, let's say you want to read an integer from an inputFile
to find out if one of the integers is 500. One way to structure a loop is:
while (fgets (buffer, sizeof (buffer), inputFile)){ sscanf (buffer, "%d", &num); if (num == 500) break; }
Here, the person reading your code should read the entire while
to find out what you are really looking for in the file. If you write this without break
:
while ((num != 500) && fgets (buffer, sizeof (buffer), inputFile)) sscanf (buffer, "%d", &num);
the loop condition itself tells the reader exactly what your code is trying to do, which makes it much easier to understand quickly. In addition, as a bonus, you have saved several lines of code.
Now imagine a more complex while
or for
while
, where break
is deep inside the loop body. It's easy to see why trying to find a break
trigger will be annoying. The presence of a correctly structured loop condition is much larger, but also self-documenting.
Of course, there are times when break
and continue
are actually good ways to write code. For example, if the condition in which the loop should end may occur in the middle of the loop, and there is a long set of statements that follow inside the loop, and the execution of these statements will add processing time without doing anything useful, and use break
. But these cases are an exception, not "most of the time."