Comparison without relational operators
Source: Quant interview at Religare Technova Problem: Write a C program to compare two integers without using relational operators (== != < <= > >=) Solution: Highlight the part between the * symbols for the answer. * Idea: subtract and inspect the sign without any relational operator. Equality: a == b iff (a ^ b) == 0, i.e. use if (!(a ^ b)). Greater/less: with 64-bit ints, d = a - b; the sign bit of d tells the answer: ((uint64_t)(a - b)) >> 63 is 1 iff a < b (Sanjoy's version). Equivalently, without shifts: if (d - abs(d)) is nonzero, d was negative so b > a; otherwise a > b (NG's version). A branch-free max uses the same sign trick: max = a - ((a - b) & ((a - b) >> 63)) for 64-bit ints. (Caveats from the thread: watch out for integer overflow in a - b, and abs() itself is usually implemented with a comparison - the sign-bit version avoids that.) Solution by Sanjoy and NG from the comments. *