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?
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With