narrowing conversion from int to long unsigned int {} is ill-formed in C++11

Wild Widow picture Wild Widow · Feb 12, 2014 · Viewed 11.7k times · Source

when I run the below code - I'm getting the warning "narrowing conversion from int to long unsigned int inside {} is ill-formed in C++11 [-Wnarrowing]. I'm using GNU 4.8 compiler.

typedef struct TableEntry
{
    unsigned long value;
    const char *label;
} TableEntry;

enum FunctionType
{
    NORMAL   = 0, 
    RANGE    = 1
};


TableEntry functionTypes[] = 
{
    {NORMAL,   "NORMAL"},
    {RANGE, "RANGE"}
};

I don't understand why compiler is considering enum as an int?
Is this a bug in GCC 4.8? Is there any workaround? Any help is appreciated.

Answer

Cheers and hth. - Alf picture Cheers and hth. - Alf · Feb 12, 2014

If practical do:

enum FunctionType
{
    NORMAL   = 0, 
    RANGE    = 1
};

typedef struct TableEntry
{
    FunctionType value;
    const char *label;
} TableEntry;


TableEntry functionTypes[] = 
{
    {NORMAL,   "NORMAL"},
    {RANGE, "RANGE"}
};

Otherwise, change the type in the struct to int, or explicitly base the enumeration on the same type as in the struct.

Btw., I the think g++ warning is unfounded and wrong, since the original code is valid C++03. Correction: As I understand it now, the diagnostic is correct, and this is a breaking change in C++11. I just couldn't believe it.


About the naming convention: those all uppercase identifiers are good for Java programmers (who are used to that convention), but in C++ they increase the chances of inadvertent text substitution. There are also the aesthetic considerations. Much win in reserving all uppercase for macros.