Main Content

MISRA C++:2008 Rule 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

Description

Rule Definition

In an enumerator list, the = construct shall not be used to explicitly initialize members other than the first, unless all items are explicitly initialized.1

Rationale

An implicitly initialized enumeration constant has a value one greater than its predecessor. If the first enumeration constant is implicitly specified, then its value is 0. An explicitly specified enumeration constant has the specified value.

If implicitly and explicitly specified constants are mixed within an enumeration list, it is possible for your program to replicate values. Such replications can be unintentional and can cause unexpected behavior.

Polyspace Implementation

The rule checker reports a rule violation whenever both of these conditions are true.

  • An enumeration uses the = construct to explicitly initialize members other than the first member.

  • The entire enumerator list is not explicitly initialized.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

This code explicitly initializes the last enumerator in Color to 7. The first enumeration constant, Red, is explicitly assigned a value of 6. Therefore, the values of Green and Orange are implicitly assigned values of 7 and 8 respectively. Green and Blue both have the value 7, which could be intentional or accidental, but is unclear.

enum Color {Red = 6, Green, Orange, Blue = 7};  //Noncompliant
enum Day {first = 1, second = 2, third = 3};  //Compliant
enum Foo {var1 = 6, var2, var3, var4};              //Compliant

The enumerator Day explicitly assigns every member and Foo explicitly assigns only the first member. These enumerators are unambiguous and does not violate this rule.

Check Information

Group: Declarators
Category: Required

Version History

Introduced in R2013b


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.