V1016. The value is out of range of enum values. This causes unspecified or undefined behavior.

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;

According to Common Weakness Enumeration, potential errors found by using this diagnostic are classified as CWE-681.

Bugs Found

Checked Projects
Collected Errors
13 303