Type Overflow and Underflow


When the value to be stored in a variable of a particular type is larger than the range of values that type can hold we have what is termed type overflow. Likewise when the value is smaller than the range of values the type can hold we have type underflow.

Overflow and underflow are only a problem when dealing with integer arithmetic. This is because C simply ignores the situation and continues on as if nothing had happened. With signed integer arithmetic adding two large positive numbers, the result of which will be larger than the largest positive signed int, will lead to a negative value being returned as the sign bit will be overwritten with data.

The situation is not quite so bad with unsigned integer arithmetic. Here all values are forced to be within range which will of course cause problems if you don’t expect overflow to occur. Adding 1 to the largest unsigned integer will give 0.

The unfortunate aspect of the matter however is that we cannot check for overflow until it has occurred. There are a number of ways to do this. For example when performing integer addition you might check the result by subtracting one of the operands from the result to see if you get the other. On the other hand you might subtract one operand from the largest integer to see if the result is greater than the second operand. If it is you know your operation will succeed. However the major flaw with these methods is that we are reducing the overall efficiency of the program with extra operations.

In general the optimum method for dealing with situations where overflow or underflow is possible is to use type long over the other integer types and inspect the results. Operations using long operands are in general slower than those using int operands but if overflow is a problem it is still a better solution than those mentioned above.

Floating point overflow is not a problem as the system itself is informed when it occurs which causes your program to terminate with a run-time error. If this happens you need to promote the variables involved in the offending operation to the largest possible and try again.

NOTE : The C standard library includes a number of exception handling functions to allow you to intercept these situations in your program.