V2552. MISRA. 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 MISRA (Motor Industry Software Reliability Association).

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:

  • MISRA-CPP-7.2.1

Bugs Found

Checked Projects
Collected Errors
14 526
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →