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

"else" statements should be clearly matched with an "if"

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Add explicit curly braces to avoid dangling else.
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way, MISRA C++ 2008 recommended
    • Covered Languages:
      C, C++, Java, Objective-C
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      1min
    • Analysis Level:
      Syntactic Analysis

      Description

      The dangling else problem appears when nested if/else statements are written without curly braces. In this case, else is associated with the nearest if but that is not always obvious and sometimes the indentation can also be misleading.

      This rules reports else statements that are difficult to understand, because they are inside nested if statements without curly braces.

      Adding curly braces can generally make the code clearer (see rule S121 ), and in this situation of dangling else, it really clarifies the intention of the code.

      Noncompliant Code Example

       if (a) 
         if (b) 
           d++; 
       else     // Noncompliant, is the "else" associated with "if(a)" or "if (b)"? (the answer is "if(b)")
         e++;
      

      Compliant Solution

       if (a) {
         if (b) {
           d++;
         } 
       } else { // Compliant, there is no doubt the "else" is associated with "if(a)"
         e++;
       }
      

      See

        Attachments

          Issue Links

          1.
          Java RSPEC-5681 Language-Specification Active Unassigned

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              massimo.paladin Massimo PALADIN
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: