I have a simple function that returns a primitive sum of NSNumbers, but doesn’t count them if they’re -1:
- (NSInteger)total {
return [[self obj1] integerValue] == -1 ? 0 : [[self obj1] integerValue] +
[[self obj2] integerValue] == -1 ? 0 : [[self obj2] integerValue] +
[[self obj3] integerValue] == -1 ? 0 : [[self obj3] integerValue];
}
In this case total will always return 0.
But if I write it like this:
- (NSInteger)total {
NSInteger ret = 0;
ret += [[self obj1] integerValue] == -1 ? 0 : [[self obj1] integerValue];
ret += [[self obj2] integerValue] == -1 ? 0 : [[self obj2] integerValue];
ret += [[self obj3] integerValue] == -1 ? 0 : [[self obj3] integerValue];
return ret;
}
total will return the correct value.
I don’t have a preference for writing it one way over the other, but I don’t see what’s wrong with the first way.
Operator precedence. The ternary operator has the third lowest precedence in C, so the addition is evaluated before it could get to the conditional part. Use parentheses: