Type No return, in function returning non-void

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 works, but I still get:

Warning: return is not returned, the function returns non-void

Although it is obvious that all cases are covered. Is there a way to handle this “right” way?

+4
source share
4 answers

The compiler does not understand that conditions ifcover all possible conditions. Therefore, he believes that the execution thread can still go through all ifs.

Since either of these conditions allows the rest to be false, you can write it as follows:

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

And since the operator returnfinally completes the function, we can shorten it to this:

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

else s.

+8

"" ?

- if. , , ,

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

, , , , if . - if, .

+4

.

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

, ,

int f( int i )
{
    return i == 0 ? 0 : ( i < 0 ? -1 : 1 );
}

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

, , .

:

                           int f(int i)

        if                      if                   if

(int > int), return    (int == int), return   (int < int), return

, if/else , , , . AST, ( ).

Besides the pure syntax, if the compiler had to rely on "possible" evaluations as well, trying to understand the behavior of your program, it would eventually need to confuse itself and probably run into a stop problem. Even if he manages to cover some cases, it is likely to raise more questions than answer, and risk a whole new level of error.

0
source

Source: https://habr.com/ru/post/1626360/


All Articles