简体   繁体   中英

#ifdef doesn't work. But why?

#ifdef doesn't work. But why? 

CGFloat maxScale;

if ( [[UIScreen mainScreen] respondsToSelector: @selector (scale)] == YES )
{
    NSLog (@"case1");
#define GLOBAL1
}
else 
{
    NSLog (@"case2");
#undef GLOBAL1
}

#ifdef GLOBAL1
NSLog (@"first");
maxScale = 1.0 / [[UIScreen mainScreen] scale];
#else
NSLog (@"second");
maxScale = 1.0;
#endif

#undef GLOBAL1

my log:case1, second. But it must be case1, first.

#define , #ifdef are pre-processor macros/conditionals. That means that the logic contained in them is compiled before your code is compiled. It is not actually part of your code.

See this guide for learning what pre-processor macros/conditionals are and do.


[EDIT]

This is what your pre-processor sees when it reads your code.

#define GLOBAL1
#undef GLOBAL1

#ifdef GLOBAL1
   //...
#else
   //...
#endif

#undef GLOBAL1

it IGNORES all other code and logic.

This is the actual code output the compiler makes:

if ( [[UIScreen mainScreen] respondsToSelector: @selector (scale)] == YES )
{
    NSLog (@"case1");
}
else 
{
    NSLog (@"case2");
}

// because the pre-processor #undef GLOBAL1
NSLog (@"second");
maxScale = 1.0;

The pre-processor code is "executed" telling the compiler how to compile, and will not be used or run during run-time.

Hope that helps!

The preprocessor does not care that the #define is inside a coded if statement - it is processed before the code and only cares about other preprocessor definitions. You can't use #defines and other preprocessor commands (such as #undef ) as code- they will not be hit each time the code enters the conditional branches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM