do-while loop has an empty body
ID |
objectivec.correctness.empty_do_while |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Suspicious Code |
Language |
Objective-C |
Description
Reports a do / 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.
Rationale
A do / while with an empty body runs its condition over and over with nothing in between, which is either a busy-wait that burns a core until the condition flips, or a loop whose body was deleted and whose condition is now the only thing left doing work. Both read the same way in a diff. The busy-wait form is the more damaging of the two on a phone, where it drains the battery and starves the thread that would otherwise change the condition.
The following code illustrates the pattern detected by this rule:
@implementation Poller
- (void)spinOnOneLine {
volatile int32_t ready = 0;
// FLAGGED: do-while loop has an empty body
do { } while (OSAtomicCompareAndSwap32(0, 1, &ready) == false);
}
- (NSInteger)drainOnce:(NSInteger)pending {
return pending - 1;
}
@end
Remediation
Restore the body if it was lost. If the loop really is a wait, replace the spin with a primitive that blocks — a semaphore, a condition variable, a dispatch group, or a KVO callback — so the thread yields instead of burning cycles. Where a spin genuinely is the right answer, state why in a comment inside the braces.