for loop with no initialiser and no increment
ID |
objectivec.maintainability.for_should_be_while |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Control Flow |
Language |
Objective-C |
Description
Reports a for loop whose initialiser and increment clauses are both empty while the condition is not, i.e. for (; cond; ). The idiomatic infinite loop for (;;) is not reported, nor is a loop that keeps either of the other two clauses. A for written inside a comment or a string literal is not reported.
Rationale
The three-clause header is what a for is for: it puts the loop variable’s setup, test and step in one place so the reader can see the loop terminates. With two of the three empty the header carries a condition and two placeholders, and the reader still has to hunt through the body for whatever advances the loop — which is exactly the reading a while asks for, minus the semicolons that suggest state which is not there.
The following code illustrates the pattern detected by this rule:
@implementation Cursor
- (void)drainQueue {
// FLAGGED: for loop with no initialiser and no increment
for (; [self hasNext]; ) {
[self takeNext];
}
}
- (BOOL)hasNext { return NO; }
- (void)takeNext { }
- (NSInteger)step:(NSInteger)i { return i - 1; }
@end