Xcode 4.6 Tip: Set Compiler Warning For Empty Loops

January 29, 2013

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: