Search code examples
c++functionswitch-statementreturn

no return in function using switch statement


I'm devoloping an application in LINUX with an older gcc version (7.something if I remember correctly). Recently I tried to run the same application on Windows. On Windows, I'm using MinGW as a compiler (with gcc 8.1.0) .

I came across this error message while compiling my application on Windows:

warning: control reaches end of non-void function [-Wreturn-type]

the code is similar to the following:

class myClass {
protected:
    enum class myEnum{
        a,
        b,
    };

    int fun(myClass::myEnum e);
}

and

int myClass::fun(myClass::myEnum e) {
    switch (e){
        case myEnum::a:{
            return 0;
        }
        case myEnum::b:{
            return 1;
        }
    }
}

I understand what the error message means, I'm just wondering why it was never an issue in LINUX.

Is this piece of code really an issue and do I have to add some dummy return statements?

Is there a branch of this function that will lead to no return statement?


Solution

  • This is a shortcoming of g++ static analyzer. It doesn't get the fact that all enum values are handled in the switch statement correctly.

    You can notice here https://godbolt.org/z/LQnBNi that clang doesn't issue any warning for the code in it's current shape, and issues two warnings ("not all enum values are handled in switch" and "controls reach the end on non-void function") when another value is added to the enum.

    Keep in mind, that compiler diagnostic is not standardized in any way - compiler are free to report warnings for conforming code, and report warnings (and compile!) for a malformed program.