Warning C33010

Unchecked lower bound for enum 'enum' used as index.

This warning is triggered if an enum is both used as an index into an array and isn't checked on the lower bound.

Remarks

Code using enumerated types as indexes for arrays will often check for the upper bound in order to ensure the index isn't out of range. Because an enum variable is signed by default, it can have a negative value. A negative array index can allow arbitrary memory to be read, used, or even executed.

Code analysis name: UNCHECKED_LOWER_BOUND_FOR_ENUMINDEX

Example

The following code generates this warning. idx is used as an index to access functions, but the lower bound is never checked.

typedef void (*PFN)();

enum class Index
{
    Zero,
    One,
    Two,
    Three,
    Max
};

void foo(Index idx, PFN(&functions)[5])
{
    if (idx > Index::Max)
        return;

    auto pfn = functions[static_cast<int>(idx)];
    if (pfn != nullptr)
        (*pfn)();
}

The following code remediates this warning by checking the lower bound as well to ensure idx isn't negative:

typedef void (*PFN)();

enum class Index
{
    Zero,
    One,
    Two,
    Three,
    Max
};

void foo(Index idx, PFN(&functions)[5])
{
    if (idx < Index::Zero || idx > Index::Max)
        return;

    auto pfn = functions[static_cast<int>(idx)];
    if (pfn != nullptr)
        (*pfn)();
}

Alternatively, the issue can be fixed by choosing an underlying type for Index that is unsigned. Because an unsigned value is always positive, it is sufficient to only check the upper bound.

typedef void (*PFN)();

enum class Index : unsigned int
{
    Zero,
    One,
    Two,
    Three,
    Max
};

void foo(Index idx, PFN(&functions)[5])
{
    if (idx > Index::Max)
        return;

    auto pfn = functions[static_cast<unsigned int>(idx)];
    if (pfn != nullptr)
        (*pfn)();
}

See also

C33011