Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-924

Loops should not have more than one "break" or "goto" statement

    Details

    • Message:
      Reduce the number of nested break and goto statements from X to Y authorized.
    • List of parameters:
      • Key: maxNumberOfTerminationStatements
      • Default value : 1
      • Description : Maximum authorized number of break/goto statements
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Legacy Key:
      SingleGotoOrBreakPerIteration
    • Covered Languages:
      C, C++, Objective-C
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      20min
    • MISRA C 2004:
      14.6
    • MISRA C 2012:
      15.4
    • MISRA C++ 2008:
      6-6-4
    • PC-Lint:
      9011

      Description

      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
        }
      }
      

      See

      • 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

        Attachments

          Issue Links

          1.
          C-Family RSPEC-4388 Language-Specification Active Unassigned

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                Anonymous
              • Votes:
                0 Vote for this issue
                Watchers:
                0 Start watching this issue

                Dates

                • Created:
                  Updated: