if condition is a literal constant
ID |
objectivec.correctness.constant_condition |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Dead Code |
Language |
Objective-C |
Description
Reports an if or else if whose condition is written as a bare literal — 0, 1, YES, NO, true, false, TRUE or FALSE — so the branch taken is fixed at compile time. Only the literal itself counts: a comparison against a constant such as if (code == 1) is a real runtime decision and is not reported. while (1) and friends are not reported either, since a literal condition there is the ordinary way to write an infinite loop. A constant used as the condition of a ternary is reported by constant-conditional-operator.
Rationale
The if states that a decision is being made, and no decision is being made: one branch is unreachable and the other runs unconditionally. Usually the line is a switch left flipped after a debugging session or a feature toggle that was hard-wired and never removed, and the cost is that it keeps working — the dead branch still compiles, still passes review, and still looks live to anyone reading the method, so the code it holds drifts out of date while appearing maintained. if (0) in particular is a way of commenting a block out that the compiler cannot warn about the way it warns about unreachable statements.
The following code illustrates the pattern detected by this rule:
@implementation Switchboard
- (void)disabledBlock {
// FLAGGED: if condition is a literal constant
if (0) {
[self legacyPath];
}
}
- (void)newPath {
}
- (void)legacyPath {
}
- (void)pump {
}
@end