Επεξεργασία

Κοινή χρήση μέσω


Compiler Warning (level 4) C4770

partially validated enum 'symbol' used as index

The compiler warns if an enum value is cast or aliased to an integer type, but the result isn't checked for non-negative or excessive values.

Remarks

This warning is new in Visual Studio 2013. It's not enabled by default. To enable it as a level 1 warning, use /w14770. For information on how to disable warnings by compiler version, see Compiler warnings by compiler version.

Example

The following code produces warning C4770:

// c4770.cpp
// compile by using: cl /GL /w14770 c4770.cpp

enum E { a  0, b, c, E_MAX };

int main(int argc, char *argv[])
{
    const E e1 = E(argc); // value unknown at compile time

    if ((int)(e1) >= E_MAX)
        return 0;

    const int n = e1 + e1;  // C4770 partially validated enum used as index

    return argv[n][n];
}

To fix the warning, you could cast the value in the check to unsigned int, which implicitly forces a non-negative value:

    if ((unsigned int)(e1) >= E_MAX) 
        return 0;

Or, explicitly check for a non-negative value:

    if ((int)(e1) >= E_MAX || (int)(e1) < 0)
        return 0;