Cute but dangerous code, finding the larger integer without using comparisons

This tip submitted by Prakash Samy on 2006-07-07 11:03:15. It has been viewed 5666 times.
Rating of 2.3 with 3 votes

Here's a dangerous but intereseting technique for finding the larger of two numbers without using realational operator. Needless to say, this kind of trick isn't really needed for performance, but it's a neat way to think about the math:

```int main()
{
int a=10, b=20;
printf( a/b ? "a is bigger" : "b is bigger" );
}
```

But it's also a lesson in why you shouldn't write code lke this. Why isn't this a good approach? First, it doesn't work if b is 0. Second, it's complicated and doesn't really express your intention; it uses the integer result as a boolean, which can be confusing. Third, it doesn't work if both a and b are negative numbers. Fourth, it won't work for floating point numbers because there will be no trunction so it will always result in a non-zero value, making it look like a is bigger. Fifth, it doesn't distinguish the case when a == b.

More tips