Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 496
user7431005 Avatar asked Aug 30 '18 19:08

user7431005


People also ask

Can you return in a switch statement?

The JavaScript switch statement can contain return statements if it is present inside a function. The function will return the value in the switch statement and the code after the switch statement will not be executed.

What happens if there is no break in a switch statement?

Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached. This continuation may be desirable in some situations. The default statement is executed if no case constant-expression value is equal to the value of expression .

Does switch case need break with return?

No. return jumps back directly to the function call returning the value after it and everything (in a function) that is after an executed return statement is ignored. So return itself can act as a break statement for functions and no further break is required.

What is not allowed in a switch statement?

The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed.


1 Answers

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.

like image 78
SergeyA Avatar answered Oct 10 '22 19:10

SergeyA