Is it a bad practice to use break in a for loop?

kiki picture kiki · Oct 13, 2010 · Viewed 171.7k times · Source

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.

Answer

smirkingman picture smirkingman · Oct 13, 2010

No, break is the correct solution.

Adding a boolean variable makes the code harder to read and adds a potential source of errors.