Or another way to phrase this would be: can the compiler assume that an instance of an enum
can only hold values it is declared to hold and optimize based on that 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?
}
}
The compiler cannot optimize out undeclared enum values. The section on the language spec that talks about enumerators says
It is possible to define an enumeration that has values not defined by any of its enumerators.
so the enumeration is allowed to have values that are not explicitly specified in the enum declaration.
In addition, the section on bitmask types gives examples that utilize undefined enum values, specifically mentioning 0 as a valid flag value.
Since it is valid to have enum values that are not declared, the compiler cannot optimize out code that utilized them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With