Unused Objects/Variables
Besides using Clang for static code analysis, you can also use it to detect unused variables and objects. The following code is one such example:
-(int) addNum:(int) num1 toNum:(int) num2 {
return (num1 + num2);
}
-(void) doSomething {
int result;
result =[self addNum:5 toNum:6];
}
When analyzed, Clang will warn you that the variable result is never used (see Figure 7).
Figure 7. Clang warning about unused variables.
Uninitialized Variables
Another potential bug that the Clang can catch is uninitialized variables. Consider the following example:
-(int) makeDecision:(int) num {
int val;
if (num>0)
val = 99;
else if (num<0) {
val = -99;
}
return val;
}
If num is equal to 0, you will have a problem with val since it has not been initialized. Running Clang will flag the warning as shown in Figure 8.
Figure 8. Clang warning about uninitialized variable.
Project Settings
If you want Clang to automatically analyze your code every-time you build your project, you can do by modifying the project settings in Xcode. In Xcode, select your project and click on the Info button (located at the top of the toolbar). Click on the Build tab and scroll down the list. Under the Build Options section, check the Run Static Analyzer options (see Figure 9).
Figure 9. Configuring Xcode to analyze your code every time you build the project
Summary
In this article, you have seen the use of Clang within Xcode to analyze your code for potential memory leaks and logic errors. Now that you have seen how easy it is to use, there is no reason for you not to use it in your next project!