And just because you can never have enough different ways to compute a simple value ... The book Hacker's Delight by Henry S. Warren, Jr. describes the sign function on page 19. It gives the the comparison predicate version described by Mark Byers as well as a couple of others. With the Microsoft compiler (v14.00.50727.762), both the /O1 and /O2 switches produce less assembly for the following version from the book:
#define sign1(x) (( x >> 31 ) | ( (unsigned int)( -x ) >> 31 ))
Than for the predicate comparison version:
#define sign2(x) (( x > 0 ) - ( x < 0 ))
It took 3.8 seconds to test 2 billion integers on my PC using sign1. It took 5.7 seconds to test the same values using the comparison predicate version (sign2):
I didn't time it, but gcc (v4.0.2) emitted the same number of assembly instructions both both of these versions of the sign function.
I would be hesitant to use the version with the shift operator, though, unless that small speed improvement was terribly critical. It depends on the signed and unsigned right shift behaving appropriately (not to mention the hard coded assumption on integer size).