Mike Flynn Mike Flynn - 1 year ago 115
Objective-C Question

Directives Arithmetic in Objective-C

My issue is based around Objective-C directives, and subtracting them. Below are my directives.

#define RECT_WIDTH IS_IPAD ? 725 : 280
#define RECT_PADDING IS_IPAD ? 50 : 10

If I
, then I get 50 and not 230. Why would this happen? The only way I can get it to work is to assign each to an int, then subtract those two.

Answer Source

This is because of the priority of operations. Your code expands to this:

NSLog(@"%d", FALSE ? 725 : 280 - FALSE ? 50 : 10);

Which, once "parenthesed" with respect to C's operator precedence rules, gets you this:

NSLog(@"%d", FALSE ? 725 : ((280 - FALSE) ? 50 : 10));

This is a frequent problem with macros. They expand nearly as a copy-paste operation, so if you don't take care, you may end up with operator priority problems (like you're having now).

You have two possibilities. Either add parentheses to your defines so this cannot happen:

#define RECT_WIDTH (IS_IPAD ? 725 : 280)
#define RECT_PADDING (IS_IPAD ? 50 : 10)

Or, since this is determined at compile-time, you may use the #if directive:

 #define RECT_WIDTH 280
 #define RECT_PADDING 10
 #define RECT_WIDTH 725
 #define RECT_WIDTH 50
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download