Why is this an issue?
Restricting the number of exits from a loop is done in the interests of good structured programming. One break
or goto
statement is acceptable in a loop since this allows, for example, for dual-outcome loops or optimal coding.
Noncompliant code example
With the default threshold of 1:
for (int i = 0; i < 10; i++) {
if (...) {
break; // Compliant
}
else if (...) {
break; // Non-compliant - second jump from loop
}
else {
...
}
}
while (...) {
if (...) {
break; // Compliant
}
if (...) {
break; // Non-compliant - second jump from loop
}
}
Compliant solution
for (int i = 0; i < 10; i++) {
if (...) {
break; // Compliant
}
}
while (...) {
if (...) {
break; // Compliant
}
}
Resources
- MISRA C:2004, 14.6 - For any iteration statement there shall be at most one break statement used for loop termination.
- 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