Rule Definition
A 'for' loop must be straightforward to read. Using too many 'break' statements in 'for' loops makes them more difficult to read.
This rule mostly applies to C code where manual clean-up may need to be performed at each step, and having several ways to exit a block can lead to more complex code.
Remediation
Try to remove the 'break' statements from the loop and to manage the end-of-loop within the loop condition part.
Violation Code Sample
for (int i = 0; i < 10; i++)
{
if (true)
{
break; // Violation
}
// ...
}
Fixed Code Sample
for (int i = 0; i < 10; i++)
{
if ( ... )
{
// do something..
break; // compliant
}
}
Reference
MISRA C++:2008, 6-6-4 - For any iteration statement there shall be no more than one break or goto statement used for loop termination.
MISRA C:2012, 15.4 - There should be no more than one break or goto statement used to terminate any iteration statement
Related Technologies
Technical Criterion
Programming Practices - Structuredness
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.