AUTOSAR C++14 Rule A7-2-1
An expression with enum underlying type shall only have values corresponding to the enumerators of the enumeration
Since R2022a
Description
Rule Definition
An expression with enum underlying type shall only have values corresponding to the enumerators of the enumeration.
Rationale
If your program evaluates an expression with enum
underlying type and
returns a value that is not part of the enumerator list of the enumeration, the behavior is
unspecified.
Compliance with this rule validates the assumption made by other rules in this standard
that objects of type enum
contain only values corresponding to the
enumerators.
To avoid unspecified behavior when evaluating expressions of type
enum
, use a switch
statement. For
example:
#include <cstdio> enum class E : size_t { Pass, Warning, Error }; E Evaluate(size_t input) noexcept { E output = E::Pass; switch (input) { case 0: { output = E::Pass; break; } case 1: { output = E::Warning; break; } case 2: { output = E::Error; break; } default: { output = static_cast<E>(0); } } return output; }
Polyspace Implementation
Polyspace® flags the use of a value that is not part of the enumerators of an enumeration.
Polyspace does not flag the use of unknown values, even if you do not check the range of
the value before you use it in the enum
expression.
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
Check Information
Group: Declaration |
Category: Required, Automated |