Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preprocessor macro and BOOL weirdness

Code below yields the output "yes defined", "no defined" and "yes". Why?

#define FOOBAR NO
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
#ifdef YES
    NSLog(@"yes defined");
#endif

#ifdef NO
    NSLog(@"no defined");
#endif

#if FOOBAR == YES
    NSLog(@"yes");
#else
    NSLog(@"no");
#endif
    // ...
}

YES and NO are not undefined, objc.h defines them as:

typedef signed char     BOOL;
#define YES             (BOOL)1
#define NO              (BOOL)0
like image 973
Morrowless Avatar asked Feb 19 '23 23:02

Morrowless


2 Answers

What is the value of NO? If it's undefined (like YES), they will both evaluate to 0.

This means your expression is essentially

#if 0 == 0

which is of course true, and thus causes the first call to be compiled.

UPDATE: Not sure how BOOL is defined, but casting to what might be a typedef:ed type is not a very good idea when dealing with the preprocessor. Remember that the the #if is evaluated by the preprocessor, not by the compiler. Read something like this for more information about expressions in the preprocessor. Especially:

The preprocessor does not know anything about types in the language.

like image 156
unwind Avatar answered Mar 06 '23 17:03

unwind


All identifieres that the preprocessor doesn't know of are replaced with 0 for evaluation in #if directives. If you don't have defined YES and NO both are 0 (and thus equal).

like image 38
Jens Gustedt Avatar answered Mar 06 '23 17:03

Jens Gustedt