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?
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.
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