Testing if an integer is at capacity means that your code will be very inefficient. For example, to add 123 you'd need to do 123 increments and 123 comparisons.
A better way would be to determine if the operation will overflow before performing the operation. For example (for unsigned integers only):
if(sum <= ULLONG_MAX - a) {
sum += a;
} else {
/* It would have overflowed */
}
This works because ULLONG_MAX - a
can not overflow. When you start looking at signed integers it becomes a larger problem because LLONG_MAX - a
can overflow (if a
is negative), and LLONG_MIN - a
can also overflow (if a
is positive). You need to test both ways:
if( ( a > 0) && (sum <= LLONG_MAX - a) {
sum += a;
} else if( ( a < 0) && (sum >= LLONG_MIN - a) {
sum += a;
} else if( a != 0) {
/* It would have overflowed */
}
Once you've determined if it would have overflowed you need to handle that case. For example; if you're using multiple integers to represent one larger integer; then (for unsigned integers):
if(sum_low <= ULLONG_MAX - a) {
sum_low += a;
} else {
sum_low -= (ULLONG_MAX - a) + 1;
sum_high++;
}
Please note that you have to be very careful to avoid accidental overflows in temporary calculations involved in handling the original (avoided) overflow.
If you use multiple signed integers to represent one larger signed integer, then the logic behind overflow handling becomes complex and error-prone. It is theoretically possible; however it's far better to separate the signs of the numbers and then do operation (or its inverse - e.g. subtracting a positive number instead of adding a negative number) on unsigned integers alone; especially if you need to use 3 or more integers to represent one huge integer, or if you need more complex operations like multiplication and division.
Of course once you start down this path you're effectively implementing your own "big number" code, and should probably find/use a suitable library instead.
Finally, if you'd like to treat your new data type like primitive data types (e.g. and be able to do things like mydatatype a = 0;
) then you're out of luck - C doesn't work this way. Essentially, C is beautiful because it doesn't allow complex things to be hidden from people trying to read/understand the code; and you'd have to use a less beautiful language like C++ if you want to hide important information from unsuspecting victims. ;-)