-
Bug
-
Resolution: Fixed
-
Low
-
Code Generation Tools
-
CODEGEN-4895
-
-
N/A
-
-
In C, an enumerated type and its enumeration constants might not have the same type. The C standard says that enumeration constants have type int ("[..] an enumeration constant has type int" [C99 6.4.4.3, 6.7.2.2]), but that the enumerated type has an underlying integral type that is implementation-defined (C99 6.7.2.2), so the compiler can make enumerated types smaller than an int. In the following case, the compiler will choose an unsigned integral type for "enum E," and as a result "e" does not have the same type as "a" and "b."
enum E
{ a, b }e;
If you use an expression like the following, the compiler knows that although "e" and "b" have different types, "b" happens to be a member of the enumeration, so the compiler will accept it as a special case without a diagnostic.
e = b;
On the other hand, if you try to work with the type of "b," as opposed to "b" itself, you may get a diagnostic. Consider the following code using the typeof extension, "x" will be considered an arbitrary signed int variable, so the compiler doesn't know it actually has the value of one of the enumeration constants, and you will get a diagnostic:
_typeof_ (a) x = b;
e = x;
You can work around this diagnostic by forcing the compiler to choose "signed int" for the underlying type of the enumerated type. You can do this by introducing a dummy enumeration constant with a negative value, as below. This forces the compiler to choose a signed type, in this case "signed int." Now, even when the compiler can't see that the right-hand-side of the assignment happens to have the value of one of the enumeration constants, they will still be of compatible types, and thus there will be no diagnostic:
enum E
{ a, b, dummy = -1 }e;