为什么该程序使用`YES`和`true`产生不同的结果? [英] Why is this program produces different result with `YES` and `true`?

查看:45
本文介绍了为什么该程序使用`YES`和`true`产生不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是完整程序.你能找出它的控制台输出吗?

Here is the full program. Can you figure out its console output?

#import <Foundation/Foundation.h>

#define kEnv YES

#if kEnv
#define x @"abc"
#else
#define x @"xyz"
#endif


#define kVersion true

#if kVersion
#define y @"abc"
#else
#define y @"xyz"
#endif

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSLog(@"x: %@; y: %@", x, y);
        NSLog(@"%@", kEnv ? @"abc" : @"cba");
        NSLog(@"%@", kVersion ? @"abc" : @"cba");
    }
    return 0;
}

在继续操作之前,您可以复制&自己粘贴,运行和签出结果.

Before moving forward, you can copy & paste, run, and checkout the result yourself.

输出为:

x: xyz; y: abc
abc
abc

任何人都可以解释原因吗?

Can anyone explain the reason?

推荐答案

YES 在< objc/objc.h>中定义为 __ objc_yes ,即编译器级符号,预处理器不知道.

YES gets defined as __objc_yes in <objc/objc.h>, and that is a compiler-level symbol, unknown to the preprocessor.

(在我的计算机上,是/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/objc/objc.h.)

(/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/objc/objc.h on my machine.)

您可以通过执行操作查看定义

You can see the definition by doing

#define T(X) #X
#define S(X) T(X)
printf("YES is: \"%s\"\n", S(YES));

C预处理器是一个有趣的野兽.:)

The C preprocessor is an interesting beast. :)

为什么

#if __objc_yes

是否表现为 __ objc_yes 为假?因为预处理器完全不知道 __ objc_yes ,只有编译器才知道.这是从手册到GNU的预处理程序,但我相信它反映了有关 #if 之后的表达式可以包含的内容的标准:

behave as if __objc_yes was false? Because __objc_yes is completely unknown to the preprocessor; it is known only to the compiler. This is from the manual to the GNU preprocessor, but I believe it reflects the standard, about what the expression after #if can contain:

[...]不是宏的标识符,这些标识符都被视为数字零.[...]

[...] Identifiers that are not macros, which are all considered to be the number zero. [...]

这篇关于为什么该程序使用`YES`和`true`产生不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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