GCC warning: how to ignore -Wswitch-default on enum

80 Views Asked by At

The following code presents 3 cases where I want or don't want GCC warnings:

# include <iostream>

enum class MyEnum { FOO, BAR, BAZ };

int main()
{
    // Case 1
    int const a = 3;
    switch(a)
    {
        case 1: std::cout << "you win !" << std::endl; break;
        case 3: std::cout << "oups... wrong !" << std::endl; break;
        // default is missing, I want a warning
    }

    // Case 2
    MyEnum const e = MyEnum::BAR;
    switch(e)
    {
        case MyEnum::FOO: std::cout << "foo" << std::endl; break;
        case MyEnum::BAZ: std::cout << "baz" << std::endl; break;
        // BAR is missing, I want a warning
    }

    // Case 3
    switch(e)
    {
        case MyEnum::FOO: std::cout << "foo" << std::endl; break;
        case MyEnum::BAR: std::cout << "bar" << std::endl; break;
        case MyEnum::BAZ: std::cout << "baz" << std::endl; break;
        // All the expected possibilities are all treated, I don't want a warning
    }
    
    return 0;
}

I can solve the case 2 without breaking case 3 by adding -Wswitch-enum.

I can solve the case 1 by adding -Wswitch-default, but it generates a warning for case 3.

I use gcc 8.5.0 (I can't upgrade).

Is there a way to warn about missing default: but NOT for enum ?

For the moment, my solution is to add a default:assert(false); after all the enum cases.

// Case 3
switch(e)
{
    case MyEnum::FOO: std::cout << "foo" << std::endl; break;
    case MyEnum::BAR: std::cout << "bar" << std::endl; break;
    case MyEnum::BAZ: std::cout << "baz" << std::endl; break;
    default: assert(false);
}

Note: I don't want to just ignore warnings, because I turn all the warnings into errors.

0

There are 0 best solutions below