$ 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?
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:
Or if you're really computing "sign" yourself and this isn't a simplification of some longer example:
else
clauses are not "clutter", they are a more obvious way of stating your intent.In this case, I'd go for the solution:
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:
Which mostly goes to show that measurement is a good idea!
Your
sign()
function isn't very efficient. Try thisSource: Bit Twiddling Hacks