Phan Văn Linh Phan Văn Linh - 6 months ago 11
Objective-C Question

Can not plus with #define variable directly

At top of my

ViewController
, I have define a
MESSAGE_SIZE
like this

#define IPHONE [UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone
#define MESSAGE_SIZE IPHONE ? 12 : 13


Inside a method, I try to access to
MESSAGE_SIZE
by 2 ways. It seems the same but produce different result

float size = MESSAGE_SIZE + 2;
NSLog(@"size = %f",size);

float size2 = MESSAGE_SIZE;
float size3 = size2 + 2;
NSLog(@"size3 = %f",size3);


I test on IPHONE and here is the Log

2016-05-27 14:59:02.992 EarCrush[8278:135453] size = 12.000000
2016-05-27 14:59:02.992 EarCrush[8278:135453] size3 = 14.000000


Hope someone explains why this happened. Any help or suggestion would be great appreciated.

Avi Avi
Answer

Preprocessor macros are fancy text-replacement commands. What happens at compile time is that

float size = MESSAGE_SIZE + 2;
NSLog(@"size = %f",size);

becomes

float size = IPHONE ? 12 : 13 + 2;
NSLog(@"size = %f",size);

I assume that IPHONE evaluates to true, so you get 12.

In the second case

float size2 = MESSAGE_SIZE;
float size3 = size2 + 2;
NSLog(@"size3 = %f",size3);

becomes

float size2 = IPHONE ? 12 : 13;  // 12
float size3 = size2 + 2;         // 14
NSLog(@"size3 = %f",size3);

You can improve your macro by use of parentheses.

#define MESSAGE_SIZE (IPHONE ? 12 : 13)

Now the first example becomes

float size = (IPHONE ? 12 : 13) + 2;
NSLog(@"size = %f",size);

which will give the expected answer of 14.

Comments