Oddness test that fails for negative values
ID |
objectivec.correctness.broken_oddness_check |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Numeric |
Language |
Objective-C |
Description
Reports a test for oddness written as x % 2 == 1, x % 2 != 1 or x % 2 > 0, in either operand order. An expression whose left operand is an absolute value (abs, labs, fabs and the like) is not reported, because the value is already non-negative there, and neither are the correct forms x % 2 != 0 and x % 2 == 0.
Rationale
In C, and therefore in Objective-C, the remainder takes the sign of the dividend: -3 % 2 is -1, not 1. Every form above therefore gets the answer wrong for negative input — x % 2 == 1 reports -3 as even, and x % 2 != 1 reports it as even a second way. The tests that accompany such code almost always use positive values, so the defect survives review and the suite, and only surfaces when a subtraction, a delta or a parsed value first turns negative in production.
The following code illustrates the pattern detected by this rule:
@implementation Counter
- (BOOL)isOdd:(NSInteger)n {
// FLAGGED: Oddness test that fails for negative values
if (n % 2 == 1) {
return YES;
}
return NO;
}
- (NSInteger)total {
return 7;
}
@end