Search code examples
c++if-statementcomparison

Comparing two integers without any comparison


Is it possible to find the greatest of two integers without any comparison? I found some solutions:

if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.


Solution

  • Subtract them and check the sign using nasty bit twiddling hacks
    http://graphics.stanford.edu/~seander/bithacks.html

    Don't do this in production code if the other programmers know where you live.