juzzlin
juzzlin

Reputation: 47885

Why do I get `warning: control reaches end of non-void function` with switch-case?

Consider code like this:

enum class Foo
{
    A, B
};

int deliverPizza(Foo foo)
{
    switch (foo) {
    case Foo::A:
        return 0;
    case Foo::B:
        return 1;
    }
}

int main()
{
    return deliverPizza(Foo::A);
}

Compiled with $ g++ -o main main.cpp -Wreturn-type:

main.cpp: In function ‘int deliverPizza(Foo)’:
main.cpp:14:1: warning: control reaches end of non-void function [-Wreturn-type]

Why is this? As far as I can see all the cases are handled within the switch. Is it that GCC doesn't understand that the cases return?

On the other hand adding default makes Clang to warn about Default label in switch which covers all enumeration values.

Upvotes: 2

Views: 439

Answers (1)

lubgr
lubgr

Reputation: 38287

You can still run into UB when you construct the enum instance via a cast expression.

return deliverPizza(static_cast<Foo>(42));

This is allowed and happily compiles. I guess the warning is pedantic with respect to such a scenario.

Upvotes: 4

Related Questions