简体   繁体   中英

Objective-C: weird ternary behavior

I have a simple function that returns a primitive sum of NSNumber s, 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:

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM