Integer Overflow And Underflow in C++ :: Part-A-17

0

Integer Overflow And Underflow

INTEGER OVERFLOW AND UNDERFLOW

Unlike the integer of pure mathematics, the integer objects in a computer are bounded. As we saw above, each integer types has a maximum value and a minimum value. If the value of a variable exceeds either of its bounds, we have what is called overflow.

EXAMPLE: Testing for Overflow

This program shows what happens when an object of type  short overflows:

                       #include  <iostream.h>

                       #include  <limits.h>

                       // Tests for overflow for type short :

                        main ()

                        {

                                    Short  n  =  SHRT_MSX  –  1;

                                    cout  <<  n++  <<  end1;

                                    cout  <<  n++  <<  end1;

                                    cout  <<  n++  <<  end1;

                                     cout  <<  n++  <<  end1;

                                     return  0;

                            }

 OUTPUT:

                         32766

                         32767

                         -32768

                         -32767

The values  “warp around”  the endpoints of 32,767 and -32,768. In other words, the value that results when  1  is added to 32,767 is -32,768. This is obviously wrong !

Most computers handle overflow this way. The value warp around, so that the number that comes after the maximum value is the minimum value. This is the worst kind error that can occur on a computer because normally there is no outside evidence that anything has gone wrong. As we shall see later, C++ fortunately provides mechanisms to help the programmer handle this problem.

Overflow is one kind of a run-time error. Another common example is division by zero. But this is not as great a problem because you will know when it happens: the program crashes! Numeric overflow is like an internal hemorrhage: you may not be aware that you are in grave danger.

Ref. By: JOHN R. HUBBARD, Ph.D. Professor of Mathematics and Computer Science, University of Richmond

——————– Thanks everyone

Share.

About Author

TN365

Leave A Reply

Powered by themekiller.com