Preprocessor Macro and BOOL Strangeness

The code below gives the output “yes defined”, “not 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 
+4
source share
2 answers

What is the value of NO ? If it is undefined (e.g. YES ), they will evaluate to 0 .

This means that your expression is essential

 #if 0 == 0 

which, of course, is true, and thus causes the merger of the first call.

UPDATE: it is not defined how BOOL defined, but casting to what typedef can be: type ed is not a good idea when working with a preprocessor. Remember that #if is evaluated by the preprocessor, not the compiler. Read this for more information on expressions in the preprocessor. Special:

The preprocessor knows nothing about types in the language.

+4
source

All identifiers that the preprocessor does not know are replaced with 0 for evaluation in the #if directives. If you have not defined YES and NO , both parameters are 0 (and therefore equal).

+4
source

Source: https://habr.com/ru/post/1437770/


All Articles