Mike Flynn Mike Flynn - 4 months ago 16
Objective-C Question

Directives Arithmetic in Objective-C

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

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


If I
NSLog("@%d", RECT_WIDTH - RECT_PADDING)
, 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

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:

#if IS_IPAD == FALSE
 #define RECT_WIDTH 280
 #define RECT_PADDING 10
#else
 #define RECT_WIDTH 725
 #define RECT_WIDTH 50
#endif