Saturday, August 01, 2009

Defining INT_MIN

It's always better to take a hard look at warnings. Warnings are potential Errors. Recently I came across an interesting warning with VC++.

warning C4146: unary minus operator applied to unsigned type, result still unsigned

A bit of googling revealed that above warning can be dangerous. To understand the underlying problem, here is my own version of INT_MIN.

#define INT32_MIN -2147483648

As 2147483648 is greater than max 32-bit signed int value (MAX_INT), it is treated as unsigned int. With this, type promotion kicks in and would fail the following condition.

if ( 1 > INT32_MIN ) // comparing two unsigned values
std::cout << "I am sure, 1 gt INT32_MIN";
else
std::cout << "Surprse! it says, 1 lt INT32_MIN";

To correctly define our own version of INT_MIN, see how it is defined in limits.h. The trick is to not to let the value to cross (signed) 32 bit int limits. The correct version should look like below.

#define INT32_MIN (-2147483647 - 1) // don't forget to put the braces around

Refrences:

1. More detailed explanation is available here
2.
warning C4146

No comments: