Minimum of two integers

From VT.Prog

Jump to: navigation, search

Note: some of the bitwise hacks discussed below are specific to C or C++.


The straightforward way to obtain the lesser of two integers:

if (a < b)
{
    min = a;
}
else
{
    min = b;
}


An indentical way using Hilarious C Operators:

min = (a < b)? a : b;


This is another way to do it (only for C++):

a <?= b;
or
min = a <? b;


In the interest of speed, it is possible to avoid incurring a branch by the use of bitwise operators:

min = b + ((a-b) & -(a<b));
Personal tools