可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
$ 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.