Does the compiler allow you to optimize a branch that depends on an enumeration that has an undeclared value?

Or another way of expressing this: can the compiler assume that the enum instance can only contain the values ​​that it is declared to store and optimize based on this assumption?

 enum MyType { A = 1, B = 2 }; const MyType C = static_cast<MyType>(3); void fun(MyType m) { switch (m) { case A: // ... break; case B: // ... break; case C: // can this be optimized away? } } 
+5
source share
1 answer

The compiler cannot optimize the values ​​of unoccupied enumeration values. The section on the language specification that talks about enumerators says:

You can define an enumeration that has values ​​that are not defined by any of its counters.

therefore, an enumeration is allowed to have values ​​that are not explicitly specified in the enumeration declaration.

In addition, the section on types of bitmass provides examples that use undefined enum values, in particular, mentioning 0 as a valid flag value.

Since it has an enum value that is not declared, the compiler cannot optimize the code that used them.

+4
source

All Articles