Compare two integers in C or C++ without comparison operators
90 bytes
If we can use stdio
, why not use its formatting capabilities to perform comparison?
main(a,b){scanf("%d%d",&a,&b);snprintf(&a,2,"%d",b-a);a&=63;putchar(51-!(a-45)-!!(a-48));}
Assumes ASCII-compatible encoding and little-endianness.
72 bytes
Quotients are rounded toward zero but right-shifts are (in practice) "rounded down". That's a dead giveaway.
main(a,b){scanf("%d%d",&a,&b);a-=b;putchar(a?a|=1,a/2-(a>>1)?60:62:61);}
65 79 bytes
Another distinguishing property of negative numbers is that they produce negative modulo.
This one doesn't depend on integer representation at all; it even works on my 8-bit excess-127 toaster!
Oh, and since we can use conio
, why not save two bytes with putch
? Now, if I could only find my copy of TurboC...
main(a,b){scanf("%d%d",&a,&b);long long d=a;d-=b;putch(d?d|=1,d%2-1?60:62:61);}
EDIT: Handle large differences assuming long long
is wider than int
.
Maybe I'm missing something in the rules, but...
81 bytes
main(a,b){scanf("%d%d",&a,&b);long long l=a;l-=b;printf("%lld%d",--l>>63,l>>63);}
Ouputs 00
if a > b
, -10
if a == b
, and -1-1
if a < b
.
64 61 characters
main(a,b){scanf("%d%d",&a,&b);for(a-=b;a/2;a/=2);putchar(a);}
Prints the character values of -1, 0, and 1 for less than, equal to, or greater than, respectively.
This implementation relies on undefined behavior for b
being of type int
and for inputs outside the range INT_MIN / 2
to INT_MAX / 2
. On platforms where signed overflow wraps around, whether 2s-complement (basically all of them) or sign-magnitude, it will fail for 25% of possible pairs of valid int
. Interestingly (to me anyway), it will work correctly on platforms where signed overflow saturates.