I'm not sure whether that would be considered cheating but you can simply exploit the implicit evaluation of integers as booleans in C's control structures. That is, you can simply branch depending on whether the sign bit is set. After all, if()
and return
are not operators. (To produce the proper return value in a single expression would be much harder.)
Below is my program, and here is a version on godbolt.
#include <stdio.h>#include <limits.h>/** @return -1, 0 or 1 indicating whether n is negative, 0 or positive, respectively, using only a bitwise operator. Depends on 2's complement integer representation.*/static int is_neg_zero_or_pos(int n){ // INT_MIN in 2's complement is only the sign bit. // If the sign bit is set, number is < 0. // Works for all int sizes. if (n & INT_MIN) { return -1; } // Use implicit int -> bool conversion: true if not zero. // Would trigger for negative values, too, but we eliminated // those above. // Works for all int sizes. if (n) { return 1; } // Not != 0, must be 0. // Works for all int sizes as well ;-). return 0;}int main(){ // a few test cases: zero (obviously), -1, 1, min and max int, // and something arbitrary. We don't depend on 32 bit ints // but we do depend on 2's complement. printf("%d\n\n", is_neg_zero_or_pos(0)); printf("%d\n", is_neg_zero_or_pos(1)); printf("%d\n", is_neg_zero_or_pos(8543276)); printf("%d\n\n", is_neg_zero_or_pos(INT_MAX)); printf("%d\n", is_neg_zero_or_pos(-1)); printf("%d\n", is_neg_zero_or_pos(-8543276)); printf("%d\n", is_neg_zero_or_pos(INT_MIN));}