st******@gmail.com wrote:
In my program, the caculated value is supposed to be no more than the
constant named MAXINT,otherwise, overflow error will be
informed.however, I cannot test if the value exceeds MAXINT within the
integer scope smaller than MAXINT,so I want to seek a measure to test
the excess without the value's comparing to MAXINT. Please let me know
if you have a good idea.
I'll assume that `MAXINT' is equivalent to `INT_MAX',
defined in <limits.h>: The largest possible value of an
`int' variable.
The C language does not define what happens when a
calculation's "mathematical" result would be outside the
range of its type. This means that a strategy of allowing
overflow to occur and then detecting it after the fact is
not reliable, because once the overflow has taken place the
state of your program is unknown. Instead, you must avoid
the overflow by testing the operands before calculating.
Such tests are not complicated, but they are cumbersome.
Rather than writing test after test after test, people usually
follow one of three strategies:
0: Just ignore the possibility of overflow and hope for
the best. Marginally acceptable in some settings, out
of the question in others.
1: Let overflow occur and try to detect it afterward. This
isn't perfectly safe, but a great many machines do produce
a predictable "wrap-around" for `int' overflow. For those
that do, overflow occurred in z = x+y iff z < x && z < y.
This is about as cumbersome than pre-testing x and y, but
sometimes you can make several unchecked calculations and
then inspect the final result to check them all at once.
2: Calculate in a wider type that you are sure will not have
overflow (for the values you're using), and then check the
final result before converting it to `int'. The wider type
might be `long' or `long long' or even an extended-precision
"bignum" package. In some cases, it may be feasible to do
the calculation in floating-point before converting back to
`int', but this approach requires considerable caution. In
some cases you can use unsigned integers, whose behavior on
"overflow" is well-defined by C.
Back in the Stone Age when I first learned to program, the
computers I used did something very useful on integer overflow:
The hardware generated an error condition and notified the program
that something untoward had happened. Because strategies #0 and #1
above have become so widespread I see little chance of this helpful
behavior being resurrected as people build new machines; a computer
maker's goal is to run as many programs as possible, not to detect
errors in the bad ones. This eases things for sloppy programmers,
but unfortunately it makes things quite difficult for careful coders
like you.
--
Eric Sosman
es*****@acm-dot-org.invalid