Gotcha: GCC and Unused Values

April 6, 2009

Subtle typos and the problems they bring, it’s enough to drive one nuts. Let me share a recent experience that will shed some light on my most recent experience. Below is a short snippet of code that show something similar to what I was recently attempting to do. It’s nothing more than a variable definition, and in one place incrementing the variable, in another I decrementing.

1
2
3
4
5
6
7
8
9
NSInteger x = 0;
 
// Increment x
x += 1;
 
...
 
// Decrement x
x -+ 1;

One small problem here, there is a typo in the code for decrementing x, which is easy to do given the + and = are on the say key.

It took some time to track down this problem as the compiler does not provide a warning for operations such as this that don’t have any effect.

Let’s add a compiler option so we receive a warning when we write a statement has no effect.

Option #1: User Defined GCC Options

- Make sure the Active SDK is set to one of the Simulator options
- Expand the Target option in the project settings
- Right click on the target
- Choose the Build settings
- Scroll to the bottom to the user defined settings
- Add an entry: GCC_WARN_UNUSED_VALUE and set the value to YES

Option #2: GCC Warning Options

- Make sure the Active SDK is set to one of the Device options
- Expand the Target option in the project settings
- Right click on the target
- Choose the Build settings
- Scroll to the section GCC 4.0 – Warnings
- Select the entry Unused Values

Either of the above will suffice, it just depends on what you have set as the Active SDK.

Upon making this change, for statements that have no effect, you will now get a warning generated by the compiler:

In an upcoming post I’ll show you how to set this as an option for all project templates.

3 comments

What exactly is the -+ operator? Is it an Objective-C thing? I wouldn’t have expected the above code to even compile.

by Trevor on Apr 6, 2009 at 8:36 pm. Reply #

Like yourself, I was surprised this even compiled, which is essentially the reason for the post. I made this as a typo and it took some time to track down the problem…

by john on Apr 6, 2009 at 9:09 pm. Reply #

I would expect “x -+ 1″ to treat the + as a unary operator, making the expression “x – (+1)”.

No, it’s not an Objective-C thing; the expression compiles just fine (and works as postulated above) in standard C.

by Glenn on Apr 29, 2009 at 1:47 pm. Reply #

Post a comment:

Required.

Required. Not published.