# Simplicity

January 30, 2012 6 Comments

How would you define an unsigned int of 32 bits (you can imagine about 64 bits) to be infinite?

some might

const unsigned int kMaxUnsignedInt = 0xFFFFFFFF;

Others (**shifting lovers**) may

const unsigned int kMaxUnsignedInt = (((1<<30) - 1) << 2 ) | 3;

Few may

const unsigned int kMaxUnsignedInt = ~0;

I did

const unsigned int kMaxUnsignedInt = -1;

What would you do?

On a side note

What would the following code do?

const unsigned int kMaxUnsigndInt = (1<<31) - 1;

Advertisements

Assuming infinity as theoretical notation, we can use any value of the range to denote it, perhaps the extreme values (0 or FFFFFFFF) are right options.

I like your code “const unsigned int kMaxUnsignedInt = -1;” as it is readable and portable. The result of “(1<<31) – 1;" sets all the bits of 32 bit integer, except the MSB. The converse of "set all the bits except LSB" can simply achieved by ~1. The later one is portable across platforms.

You should try the “const unsigned int kMaxUnsigndInt = (1<<31) – 1;" (on a machine) and try explaining what happened 🙂

Dude, I hope I got the issue.

I got “warning: integer overflow in expression” on G++ compiler version 4.4.5, Ubuntu Linux (same warning even with GCC as a C file). I have used AMD Athlon X2 machine. Here is what I have interpreted.

In C/C++ the integral literals will have type ‘int’ associated with them. I mean any integral literal will be treated as “signed int” type by the compiler.

The shift left of literal ‘1’ by 31 positions will create a signed literal that is least value of 32 bit machine in 2’s complement form. As per limits.h file this least value is represented as INT_MIN (numerical value –2147483648 or 0x80000000). Subtracting 1 from this least possible value will virtually create underflow, hence the warning. At this point if we print this expression as an “int” we should get -2147483649 on the screen. It is impossible, so the compiler warns the programmer.

However, the subtraction of 1, will result in roll back of the binary system. Conversion of the rolled-back number (0x7FFFFFFF) to “unsigned int” causes the value (2147483647) to fall under positive scale of integer limits. We will get the numerical value 2147483647 on the screen.

Good example on the difference between practice and theory. Am I missing something to understand, please let me know.

@Venki

That is a very good explanation. Thanx 🙂

Any (simple) fix you suggest?

🙂 Answer in your comment itself, Keep It Simple and Stupid (KISS). As mentioned by you in the original post, I would prefer,

const unsigned int kMaxUnsignedInt = (unsigned)-1;

True !

But just for completion, since these situations occur very frequently (and for people who prefer shooting themselves in the foot) the shift here done is (unsigned int)1<<31