Ashutosh Iddya said:
I am performing an integer count of a particular operation in my program.
After a sufficiently large value an overflow occurs. At the moment I have
gone around the problem by declaring it as a double, even that has its
limits. Is there a method of preventing this overflow or some method of
recovering from it. Any help in this regard would be greatly appreciated.
Using double is probably the wrong solution. If you repeatedly add 1
to a double variable, you'll never get an overflow, just a loss of
precision; eventually, (d + 1.0 == d).
The type "long long" is guaranteed to be at least 64 bits, which
should be more than enough for whatever it is you're counting. This
type is new in C99, but many C90 compilers support it as an extension.
(Since the C90 standard doesn't specify "long long", it's
theoretically possible that a C90 compiler could provide a "long long"
type that's smaller than 64 bits, but I don't think anyone has ever
done that.)
If 32 bits is enough, use long (or unsigned long).
If 32 bits isn't enough, and you don't care about portability to
systems that don't support long long, use long long (or
unsigned long long).
Be aware that a C90 implementation that supports long long as an
extension may not necessarily support everything that goes with it,
particularly the printf formats.
If you can't use long long, you might try using a pair of unsigned
longs (untested code follows):
unsigned long count_hi = 0;
unsigned long count_lo = 0;
...
for (...) {
count_lo ++;
if (count_lo == 0) count_hi ++;
}
Note the use of unsigned types. Overflow is well-defined for unsigned
types; it wraps around. Overflow for signed types causes undefined
behavior; wraparound is common, but not guaranteed.