Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default case compilation when switching over all items of an enum class

Tags:

c++

enums

c++11

Why does the following switch even compiles the default case since it covers all items of the enum class? I would have thought that this was the reason for having strong enum class in the first place.

As to why I would like to have a default even though I know that I cover all cases : This safe-guards me against my future careless-ness (and that of other coworkers)

enum class E {
    a,
    b
};

int main()
{
    E c = E::b;
    switch (c) {
        case E::a:
        case E::b:
            std::cout << "pass" << std::endl;
            break;
        default:
            static_assert(false, "This explodes!");
    }    
}

Proof

like image 234
Gurg Hackpof Avatar asked Oct 05 '22 16:10

Gurg Hackpof


1 Answers

Because the compile can't know if someone casted an illegal value to the enum type. Consider:

E c = static_cast<E>( 42 );

The cast will compile without a warning (or even an error) as you are explicitly telling the compiler "I know what I'm doing, don't check the value". In practice, this sadly happens more often than you think. :(

Also, all code needs to be valid, even if it is later removed as unreachable. A static_assert(false,...) will fire at compile-time, independent of what would happen at run-time.

like image 87
Daniel Frey Avatar answered Oct 13 '22 12:10

Daniel Frey