What to do about wrong “control reaches end of non

2019-04-28 13:53发布

$ cat t.cpp
int sign(int i) {
    if(i > 0) return 1;
    if(i == 0) return 0;
    if(i < 0) return -1;
}
$ g++ -c t.cpp -Wall
t.cpp: In function ‘int sign(int)’:
t.cpp:5: warning: control reaches end of non-void function
$

What do I do about this?

Stop using -Wall as it's clearly wrong? Add a bogus return 0 at the end? Clutter the code with "else" clauses?

标签: c++ gcc warnings
4条回答
Lonely孤独者°
2楼-- · 2019-04-28 14:14

If you don't want to add "else" clauses because they would make the code longer, then perhaps you would like to remove the final "if" and make the code shorter:

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

Or if you're really computing "sign" yourself and this isn't a simplification of some longer example:

int sign(int i) {
    return (i>0) ? 1 : ((i<0)?-1:0);
}
查看更多
ら.Afraid
3楼-- · 2019-04-28 14:22

else clauses are not "clutter", they are a more obvious way of stating your intent.

查看更多
虎瘦雄心在
4楼-- · 2019-04-28 14:33

In this case, I'd go for the solution:

int sign(int i)
{
    if (i > 0)
        return 1;
    else if (i == 0)
        return 0;    
    else
        return -1; // i<0
}

That is, I would add two else clauses - to make the code more symmetric, rather than because it makes any difference to the object code generated.

I did some experimentation. I expected the one-line version using the the ternary operator twice to generate the same code as the longer. However, testing on Solaris 10 (SPARC) with GCC v4.3.2 shows that the ternary operator version is consistently 12-16 bytes smaller than the 'if' version. However, the presence or absence of the extra else does make no difference. (Adding register made no odds, as I'd expect.) Added I also looked at Christoph's solution with 'return (i > 0) - (i < 0);' - a variant I'd not seen before. The code sizes were:

       Unoptimized     Optimized (-O5)
 if      166             110
 ?:      150              98
 >-<     122              98

Which mostly goes to show that measurement is a good idea!

查看更多
叛逆
5楼-- · 2019-04-28 14:36

Your sign() function isn't very efficient. Try this

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

Source: Bit Twiddling Hacks

查看更多
登录 后发表回答