Empty loop bodies

Quick quiz — what's wrong with this code:

You, yes you at the back, that shouted out "your opening brace is on the wrong line!". Shaddup.

Anyway, there's a fair chance you spotted it: the if statement has a semicolon straight after it. This means the code inside in the braces will always be executed, regardless of evaluation of the if statement.

Every few months I accidentally write something along the lines of the above code. Of course, I don't simply type it without thinking; it's the consequence of tidying up or refactoring some existing code. The extra semicolon gets pulled in from some earlier revision of the code and my eye just doesn't spot it. I then proceed to spend quite some time maddened and baffled as to why my code's not behaving as I'm sure it should.

Eventually I spot the mistake, remove that extra semicolon, slap myself on the forehead, and go back to work.

But no more! Happily, Clang features a compiler warning: Turn on CLANG_WARN_EMPTY_BODY — "Empty Loop Bodies" as Xcode titles it — and you'll now get a compiler warning for the above code. Fantastic!

I believe the same holds true for while, do, and for loops suffering the same mistake, but haven't actually tested it yet.

Note: When I first filed a radar asking for this feature, Apple came back saying it had been addressed in Xcode 4.6. Thus, I assumed it was a feature new to 4.6. The original version of this blog post stated so. A quick bit of testing with an older Xcode reveals that to be false though, and the warning has been implemented since at least 4.5.2. Sorry!

© Mike Abdullah 2007-2015