On break
and continue
I don't think there's anything fundamentally wrong with a break
or continue
. I think the motivation to avoid them is really has to do more with readability than anything else. Consider the following loops (not strictly c/c++ code):
// loop 1
for(int i = 0; i < a.length; i++)
{
if (!found(a[i]))
continue;
result = a[i];
break;
}
// loop 2
for(int i = 0; i < a.length; i++)
{
if (found(a[i]))
{
result = a[i];
break;
}
}
// loop 3
{
bool resultFound = false;
for(int i = 0; !resultFound && i < a.length; i++)
{
if (found(a[i]))
{
result = a[i];
resultFound = true;
}
}
}
All three of these loops run essentially the same code, but are written in slightly different ways. The real question is which one most effective conveys the author's intent?
loop 1 - very bad. The logic here seems to be inverted, and the continue
is pretty much gratuitous. If translated to English this would read something like:
Loop through the list while the item is not found, but if it is set the result then stop.
loop 2 - good. This is how such loops are generally written. If translated to English this would read something like:
Loop through the list and if the item is found, set the result then stop.
loop 3 - slightly bad. The break / continue logic is found in the condition of the for
loop, which is not as common. It means if someone reading your code wants to know what
will happen next, they have to go back to the top of the loop. A break
(as in loop 2)
specifies that logic in exactly one place. If translated to English this would read something like:
Loop through the list while the item is not found and if an item is found, set the result.
On the ?:
operator
Again, there's nothing fundamentally wrong with it. It's really a matter of personal style and readability.
// Good uses of conditional operator
string result = (someBool) ? "YES" : "NO";
string oddness = (someInt % 2 == 0) ? "even" : "odd";
// Bad use of conditional operator
int result = ConditionA() ? (ConditionB() ? 0 : 1) : (ConditionC() ? 2 : 3);
Again the programmers intent is pretty clear in the first two examples, but is much more obscured in the last.