Main Content

Unnecessary large enum base type

Base type of enumeration is larger than necessary to hold enumerators

Since R2026a

Description

This defect occurs when the base type of an enum object is larger than necessary. For example, consider the enumeration myEnum:

enum class myEnum : uint64_t { ZERO, ONE, TWO, THREE = UINT16_MAX };
The largest enumerator in this enum object has the value UINT16_MAX. That is, a base type of uint16_t is sufficient to hold the enumerators. But the base type is specified as uint64_t, which is unnecessarily large. Polyspace® reports a defect.

Risk

Using unnecessarily large base type for enumerations results in using more memory than necessary during program execution.

Fix

To fix this defect, use an enumeration base type that is no larger than necessary to hold the largest enumerator. For example:

enum class myEnum : uint16_t { ZERO, ONE, TWO, THREE = UINT16_MAX };

Performance improvements might vary based on the compiler, library implementation, and environment that you are using.

Examples

expand all

In this example, the enumeration object Color has three enumerators, with default values 1, 2, and 3. Because no base type is specified, the compiler uses the default 64-bit or 32-bit integer, which is larger than necessary to hold the largest enumerator value. Similarly, the enumeration object myEnum has enumerator values up to UINT8_MAX + 2. The base type uint64_t is unnecessarily large. Polyspace reports defects.

#include <cstdint>

enum class Color {
    Red,
    Green,
    Blue
};

enum class myEnum: uint64_t {
    A = UINT8_MAX,
    B,
    C,
};

Correction — Use base types that are no larger than necessary

To fix this defect, use a base type that is large enough to hold the largest enumerator, but no larger. For instance, the base type unit8_t can hold all enumerators of Color while a base type uint16_t can hold the enumerators of myEnum.

#include <cstdint>

enum class Color: uint8_t {
    Red,
    Green,
    Blue
};

enum class myEnum: uint16_t {
    A = UINT8_MAX,
    B,
    C
};

Result Information

Group: Performance
Language: C++
Default: Off
Command-Line Syntax: ENUM_BASE_TYPE_TOO_LARGE
Impact: Medium
PQL Name: std.defects.ENUM_BASE_TYPE_TOO_LARGE

Version History

Introduced in R2026a