Xcode 4.6 Tip: Set Compiler Warning For Empty Loops

With the release of Xcode 4.6 you can set a compile time warning when you inadvertently write a loop which has an empty body. For example, the semi-colon at the end of the ‘if’ statement below is a problem:

- (void)doSomething:(int)x
{
  // Semi-colon at end of 'if'
  if (x == 0);
  {
    NSLog(@"Made it here...");
  }
 
...
 
}

Which is really equivalent to the following, as the semi-colon ends the if statement:

if (x == 0);
 
NSLog(@"Made it here...");

The runtime results were even more bizarre when I tried the following:

while (x > 0);
{
  NSLog(@"Made it here as well...%d", x);
  x--;
}

In Xcode 4.6, you can set a compiler flag to generate a warning to catch such erroneous code:

Inside the Build Settings, search for CLANG_WARN_EMPTY_BODY, set the flags to Yes:

The compiler will now generate a warning that will look as follows:

  1. I’d rather put the ‘{‘ on the same line instead of a new line.
    Then you’ll never have this problem

    • I agree, it would be much easier to spot the semi-colon if you have the { on the same line. However, for those who prefer to have the { on a separate line (myself included) this compiler warning can be quite helpful.

Comments are closed.