当将true重定义为false时,预期的输出是什么?反之亦然? [英] What is the expected output when redefining true to false and vice versa?

查看:189
本文介绍了当将true重定义为false时,预期的输出是什么?反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< iostream> 
#define true false
#define false true
int main(){
std :: cout<假<<真正;
}

为什么输出01?


然而,我们可以考虑另一个类似的例子,具有良好定义的行为和相同的结果。考虑:

  int TRUE = 1; 
int FALSE = 0;

#define TRUE FALSE
#define FALSE TRUE

std :: cout< FALSE<<真正;

使用 FALSE 作为宏 FALSE ,并被该宏的替换列表替换,该替换列表是单个令牌 TRUE 。然后重新扫描该替换 以替换更多的宏。



替换中的 TRUE 然后被标识为宏,并被替换为替换列表,单个标记 FALSE



如果我们继续重新扫描和替换,我们将结束一个无限循环,所以C(和C ++)预处理规范说明



由于在此最终替换列表中替换 FALSE 会导致递归,宏替换停止,我们留下 FALSE ,这是 int 的名称,值为 0


#include <iostream>
#define true false
#define false true
int main() {
    std::cout << false << true;
}

Why does it output "01"?

解决方案

As Jerry Coffin notes, you cannot define a macro with a name that is a keyword.

However, we could consider another, similar example, with well-defined behavior and the same result. Consider:

int TRUE = 1;
int FALSE = 0;

#define TRUE FALSE
#define FALSE TRUE

std::cout << FALSE << TRUE;

When you use FALSE, it is identified as the macro FALSE and is replaced by that macro's replacement list, which is the single token, TRUE. That replacement is then rescanned for further macros to replace.

The TRUE in the replacement is then identified as a macro and is replaced by its replacement list, which is the single token FALSE. That replacement is again rescanned.

If we continued on rescanning and replacing, we'd end up in an infinite loop, so the C (and C++) preprocessing specifications state that macro replacement never recurses within a replacement list.

Since replacement of FALSE in this final replacement list would result in recursion, macro replacement stops and we are left with FALSE, which is the name of an int with a value of 0.

这篇关于当将true重定义为false时,预期的输出是什么?反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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