With the release of Xcode 3.2 (available with Mac OX 10.6 – Snow Leopard) you can easily run a static analysis check on your code, thanks to integration of Clang. If you’ve worked with Clang prior to its integration of Xcode, you already know just how cool this is for . If you are new to Clang, you owe it to yourself to check it out.
Static analysis does a deeper parsing of your code than a traditional compilation. It looks through each potential code path and can find potential problems that are not obvious to the compiler (and may be missed by you as well).
How it Works
The code below compiles just fine, no warnings. However, Xcode 3.2 will flag a few potential problems when running an analysis of the code. To run the analyzer, from the Build menu, choose Build and Analyze.
if (x < 0)
positiveFlag = NO;
else if (x > 0)
positiveFlag = YES;
If you look in the Build Results window, you’ll see more information:
- Variable ‘positiveflag’ declared without an initial value
- Uninitialized or undefined value returned to caller
The problem occurs in this code if the value of x == 0, given the variable positiveflag has no default value set, it may not return what you expect.
Showing Control Flow
Here’s an interesting option you have within the integration of static analysis in Xcode – click on one of the entries in the Build Results window (as shown below):
and Xcode will highlight the flow of the code, and help you pinpoint the potential problem:
Run Static Analysis with Each Build
By default, you request a static analysis of your code by selecting Build and Analyze in the Build menu. If you would like a static analysis run whenever you build a project with the debug configuration, you can check the Run Static Analyzer in the Build Options as shown in the image below: