user3474378
user3474378

Reputation: 21

handling overflow in Objective C

I'm building a hex calculator in objective-c. My problem is dealing with long long values that would overflow when multiplied.

When I add values before I add i check that the value would not overflow by doing something like this.

long long leftToAdd = LLONG_MAX - self.runningTotal;

if (self.selectedNumber <= leftToAdd) {
    self.runningTotal += self.selectedNumber;

} else {
    self.selectedNumber -= leftToAdd;   
    self.runningTotal = self.selectedNumber-1;

    self.overflowHasOccured = YES;   
}

if the value would overflow it takes the overflow value (without actually overflowing) and adds an overflow notification. I was hoping to find a way to do this same type of thing but for multiplication, can anyone help with this?

here's what i have so far.

// if - value would not overflow //
if (self.runningTotal > 0 && self.selectedNumber > 0 
    && LLONG_MAX/self.runningTotal >= self.selectedNumber) {

    self.runningTotal *= self.selectedNumber;

// else - handle overflow //
} else {


}

and as a side question would i need to do a similar check for division?

Upvotes: 0

Views: 562

Answers (1)

CRD
CRD

Reputation: 53000

You could check for overflow in multiplication following the same pattern you use for addition - for the later you use subtraction to determine the bound, for the former you would use division:

long long canMultiplyBy = LLONG_MAX / self.runningTotal;

In all cases if you are supporting signed numbers you have to consider underflow as well. Division requires a divide by zero check.

In the C library there are functions for checked arithmetic, lookup check_int64_mul to find the lot (they are all described on the same manual page). These will be efficient and operate directly with primitive value types are you are now doing.

The Clang compiler also provides some checked arithmetic builtin functions, these differ from the C library functions in returning a bool indications and being defined for int, long and long long types rather than int32 and int64. See Checked Arithmetic Builtins.

There are also NSDecimal - a value type, and NSDecimalNumber - an object type built over the former. These provide both extended precision, up to 38 decimal digits, and control over overflow, underflow, divide-by-zero, etc. See NSDecimalNumberBehaviors and NSDecimalNumberHandler.

HTH

Upvotes: 2

Related Questions