Why does 'typeof enum constant' generate a warning when compared to a variable of enum type?

Quoting directly from C11, chapter §6.7.2.2, Enumeration specifiers,

Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined.

So, the type of the enum variable is not defined by standard. It can be any of the above.

OTOH, FOO being an enumeration constant, typeof(FOO) will give you int, as the standard mandates

An identifier declared as an enumeration constant has type int.

which is being used as the type for f2.

Now, if enum is unsigned int on your implementation, so is f1 and, f2 is int.

Next, you get the warning.

How can I fix this problem?

Well, if you change the type of f2 to typeof(Baz), which gives the type of the enum, then both the types of f1 and f2 will be same. Compiler will be happy.

SEE LIVE HERE


It's a known "bug" in the C standard. Enumeration constants are guaranteed to be of type int, while enumeration variables are of implementation-defined integer type.

See this for references.

Tags:

C

Enums

Gcc