How do I programmatically return the maximum of two integers without using any comparison operators and without using if, else, etc?
This is kind of cheating, using assembly language, but it's interesting nonetheless:
// GCC inline assembly
int max(int a, int b)
{
__asm__("movl %0, %%eax\n\t" // %eax = a
"cmpl %%eax, %1\n\t" // compare a to b
"cmovg %1, %%eax" // %eax = b if b>a
:: "r"(a), "r"(b));
}
If you want to be strict about the rules and say that the cmpl instruction is illegal for this, then the following (less efficient) sequence will work:
int max(int a, int b)
{
__asm__("movl %0, %%eax\n\t"
"subl %1, %%eax\n\t"
"cmovge %0, %%eax\n\t"
"cmovl %1, %%eax"
:: "r"(a), "r"(b)
:"%eax");
}