Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the compiler allowed to optimize out a branch that depends on an enum having an undeclared value? [duplicate]

Tags:

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?
    }
}
like image 830
Ryan Haining Avatar asked Sep 02 '16 22:09

Ryan Haining


1 Answers

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.

like image 97
1201ProgramAlarm Avatar answered Sep 22 '22 16:09

1201ProgramAlarm