>
>
>
V3531. AUTOSAR. Expressions with enum u…


V3531. AUTOSAR. Expressions with enum underlying type should have values corresponding to the enumerators of the enumeration.

This diagnostic rule is based on the software development guidelines developed by AUTOSAR (AUTomotive Open System ARchitecture).

The analyzer has detected an unsafe cast of a number to an enumeration. This number may be out of the range of enum values.

Consider the following example:

enum TestEnum { A, B, C };
TestEnum Invalid = (TestEnum)42;

Since the standard does not specify a base type for enum, casting a number that is out of the range of enum elements results in unspecified behavior in standards older than C++17 and undefined behavior starting with C++17.

To avoid this, make sure you check numbers before casting them. As an alternative, you could explicitly specify the base type for enum or use 'enum class' whose base type is 'int' by default.

The fixed code – version 1:

enum TestEnum { A, B, C, Invalid = 42 };

Version 2:

enum TestEnum : int { A, B, C };
TestEnum Invalid = (TestEnum)42;

Version 3:

enum class TestEnum { A, B, C };
TestEnum Invalid = (TestEnum)42;

This diagnostic is classified as:

  • AUTOSAR-A7.1.2