while loop has an empty body
ID |
objectivec.correctness.empty_while_block |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Suspicious Code |
Language |
Objective-C |
Description
Reports a while loop whose body holds nothing at all, whether the braces are written on one line or across several. A body carrying a statement, or a comment explaining that the spin is deliberate, is not reported. The trailing while of a do / while is not reported here.
Rationale
A while with an empty body spins on its condition and does nothing else. If the condition has no side effect the loop cannot terminate, and the app hangs on that thread; if it does have one, the loop is a busy-wait that keeps a core at full occupancy until the condition flips. On a phone that shows up as heat and battery drain, and it can starve the very thread that would change the condition. The third possibility — that the body was deleted — leaves a loop that still costs its iterations and produces nothing.
The following code illustrates the pattern detected by this rule:
@implementation Reader
- (void)spinOnOneLine {
volatile BOOL ready = NO;
// FLAGGED: while loop has an empty body
while (!ready) { }
}
- (void)consume:(id)item {
NSLog(@"%@", item);
}
@end