How do I programmatically return the max of two integers without using any comparison operators and without using if, else, etc?

MrDatabase picture MrDatabase · Oct 22, 2008 · Viewed 13.7k times · Source

How do I programmatically return the maximum of two integers without using any comparison operators and without using if, else, etc?

Answer

plinth picture plinth · Oct 22, 2008

max: // Will put MAX(a,b) into a

a -= b;
a &= (~a) >> 31;
a += b;

And:

int a, b;

min: // Will put MIN(a,b) into a

a -= b;
a &= a >> 31;
a += b;

from here.