Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type No return, in function returning non-void

Tags:

c++

My C++ code looks like this:

int f(int i){
    if (i > 0) return 1;
    if (i == 0) return 0;
    if (i < 0) return -1;
}

It's working but I still get:

Warning: No return, in function returning non-void

Even though it is obvious that all cases are covered. Is there any way to handle this in "proper" way?

like image 565
user31027 Avatar asked Jan 28 '16 14:01

user31027


1 Answers

The compiler doesn't grasp that the if conditions cover all possible conditions. Therefore, it thinks the execution flow can still fall through past all ifs.

Because either of these conditions assume the others to be false, you can write it like this:

int f(int i) {
    if (i > 0) return 1;
    else if (i == 0) return 0;
    else return -1;
}

And because a return statement finally terminates a function, we can shorten it to this:

int f(int i) {
    if (i > 0) return 1;
    if (i == 0) return 0;
    return -1;
}

Note the lack of the two elses.

like image 162
cadaniluk Avatar answered Nov 02 '22 17:11

cadaniluk