Is it a bad practice to use break
statement inside a for
loop?
Say, I am searching for an value in an array. Compare inside a for loop and when value is found, break;
to exit the for loop.
Is this a bad practice? I have seen the alternative used: define a variable vFound
and set it to true when the value is found and check vFound
in the for
statement condition. But is it necessary to create a new variable just for this purpose?
I am asking in the context of a normal C or C++ for loop.
P.S: The MISRA coding guidelines advise against using break.
Lots of answers here, but I haven't seen this mentioned yet:
Most of the "dangers" associated with using break
or continue
in a for loop are negated if you write tidy, easily-readable loops. If the body of your loop spans several screen lengths and has multiple nested sub-blocks, yes, you could easily forget that some code won't be executed after the break. If, however, the loop is short and to the point, the purpose of the break statement should be obvious.
If a loop is getting too big, use one or more well-named function calls within the loop instead. The only real reason to avoid doing so is for processing bottlenecks.