What to do about wrong “control reaches end of non-void function” gcc warning?

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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

回答1:

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); } 


回答2:

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

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

Source: Bit Twiddling Hacks



回答3:

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!



回答4:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!