0) return 1; if(i == 0)...">

What to do with the wrong "control until the end of the non-void" gcc warning function?

$ 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 should I do with this?

Stop using -wall because it is clearly wrong? Add fictitious income 0 at the end? Break code with else clauses?

+6
c ++ gcc warnings
source share
4 answers

If you don't want to add β€œelse” clauses because they will make the code longer, then you might want 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 really calculate the β€œsign” yourself, and this is not a simplification of a longer example:

 int sign(int i) { return (i>0) ? 1 : ((i<0)?-1:0); } 
+17
source share

Your sign() function is not very efficient. try it

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

Source: Tweedling Hacks Bit

+11
source share

In this case, I would go for a 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 additional sentences - to make the code more symmetrical, and not because it has any value for the generated object code.

I experimented a bit. I expected that the single-line version using the triple operator will generate the same code twice as longer. However, testing Solaris 10 (SPARC) with GCC v4.3.2 shows that the ternary operator version is sequentially 12-16 bytes less than the if version. However, the presence or absence of excess does not matter. (Adding a register did not make any chance, as I expected.) Added I also looked at Christophe's solution with "return (i> 0) - (i <0); - an option that I have not seen before. Code sizes:

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

It basically shows that measurement is a good idea!

+5
source share

else articles are not β€œriots”; they are the more obvious way to state your intentions.

+3
source share

All Articles