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

"enum" members other than the first one should not be explicitly initialized unless all members are explicitly initialized

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Legacy Key:
      EnumPartialInitialization
    • Covered Languages:
      C, C++, Objective-C
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      20min
    • MISRA C 2004:
      9.3
    • MISRA C++ 2008:
      8-5-3
    • PC-Lint:
      9148

      Description

      If an enumerator list is given with no explicit initialization of members, then C/C++ allocates a sequence of integers starting at zero for the first element and increasing by one for each subsequent element.

      An explicit initialization of the first element, as permitted by this rule, forces the allocation of integers to start at the given value. When adopting this approach it is essential to ensure that the initialization value used is small enough that no subsequent value in the list will exceed the int storage used by enumeration constants.

      Explicit initialization of all items in the list, which is also permissible, prevents the mixing of automatic and manual allocation, which is error prone.
      However, it is then the responsibility of the developer to ensure that all values are in the required range, and that values are not unintentionally duplicated.

      Noncompliant Code Example

      enum color { red = 3, blue, green, yellow = 5 }; // Noncompliant; both green and yellow = 5
      

      Compliant Solution

      enum color { red = 3, blue = 4, green = 5, yellow = 5 }; // Compliant
      

      See

      • MISRA C:2004, 9.3 - In an enumerator list, the "=" construct shall not be used to explicitly initialize members other than the first, unless all items are explicitly initialized.
      • MISRA C++:2008, 8-5-3 - In an enumerator list, the = construct shall not be used to explicitly initialize members other than the first, unless all items are explicitly initialized.

        Attachments

          Issue Links

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

            Activity

              People

              • Assignee:
                evgeny.mandrikov Evgeny Mandrikov
                Reporter:
                Anonymous
              • Votes:
                0 Vote for this issue
                Watchers:
                2 Start watching this issue

                Dates

                • Created:
                  Updated: