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.
Using
break
as well ascontinue
in afor
loop is perfectly fine.It simplifies the code and improves its readability.
It's perfectly valid to use
break
- as others have pointed out, it's nowhere in the same league asgoto
.Although you might want to use the
vFound
variable when you want to check outside the loop whether the value was found in the array. Also from a maintainability point of view, having a common flag signalling the exit criteria might be useful.Ofcourse,
break;
is the solution to stop the for loop or foreach loop. I used it in php in foreach and for loop and found working.It depends on the language. While you can possibly check a boolean variable here:
it is not possible to do it when itering over an array:
Anyway,
break
would make both codes more readable.On MISRA 98 rules, that is used on my company in C dev, break statement shall not be used...
Edit : Break is allowed in MISRA '04
You can find all sorts of professional code with 'break' statements in them. It perfectly make sense to use this whenever necessary. In your case this option is better than creating a separate variable just for the purpose of coming out of the loop.