Exceed Integer Limits

◀ Assignment Operator Between Two Structure Instances▶ Short-Circuit Evaluation
Amazon As most of you know, there are limits to how big and small an integer can go. If you go beyond those limits, funny things happen. In this section we will discuss this topic.

There are basically three C++ integer types: short, int, and long. Standard C++ guarantees a minimum size for each of them:
  • A short is at least 16 bits.
  • An int is at least as big as short.
  • A long is at least 32 bits and at least as big as int.
There is an easy way to find out the exact size of your system’s integers. You can simply print symbolic constants provided by <climits> (or <limits.h> for older implementations) in a program. You can also use sizeof on a type to see how big it is in bytes. For example, sizeof(int) gives you 4 and sizeof(short) gives you 2 on most systems.

Now that we understand that, let’s turn our attention to the potential traps we could fall into if we are not careful enough. I have the following declarations:
int john=0;
unsigned int cheryl=0;
I deduct one from john and cheryl and print their values:
john--;
cheryl--;
cout<<"John: " <<john<<" Cheryl: "<<cheryl;
I got John: -1 Cheryl: 4294967295. Now I reinitialize their values:
john=INT_MAX;
cheryl= INT_MAX;
Add one to john and cheryl and print their values:
john++;
cheryl++; cout<<"John: " <<john<<" Cheryl: "<<cheryl;
I got John: -2147483648 Cheryl: 2147483648

Your intuition probably tells you that –2147483648 is the minimum value of int and 4294967295 is the maximum value of unsigned int, and you hit the nail right on the head!

john is an int, which ranges from -2147483648 to 2147483647. cheryl is an unsigned int, which ranges from 0 to 4294967295.

As we can see, when you subtract one from the minimum value of unsigned int, you get the maximum value of unsigned int; when you add one to the maximum value of int, you get the minimum value of int.


The overflow and underflow behavior can be depicted as a circle: if you move past the limit of a type, you get the value at the other extreme of the range.
You can also try the following code in your program:
cout<<INT_MAX<<endl;
cout<<INT_MAX*2<<endl;  /* print out –2 */
Try to figure out why the output is –2. You can use a narrower analogous situation such as use 5 as the maximum value and –6 as the minimum value.

Next we’ll look at short-circuit evaluation and how we can use it effectively!

◀ Assignment Operator Between Two Structure Instances▶ Short-Circuit Evaluation

fShare
Questions? Let me know!