预处理程序宏和BOOL异常 [英] Preprocessor macro and BOOL weirdness

查看:67
本文介绍了预处理程序宏和BOOL异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码产生输出"yes defined","nodefined"和"yes".为什么?

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
    // ...
}

是和否不是未定义的,objc.h将它们定义为:

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

typedef signed char     BOOL;
#define YES             (BOOL)1
#define NO              (BOOL)0

推荐答案

NO的值是什么?如果未定义(例如YES),它们都会评估为0 .

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.

更新:不确定BOOL的定义方式,但是在处理预处理器时,将其强制转换为typedef:ed类型不是一个好主意.请记住,#if是由预处理器而不是编译器求值的.阅读类似于的内容,以获取有关预处理器中表达式的更多信息.特别是:

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.

这篇关于预处理程序宏和BOOL异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆