三重平等条件带来奇怪的结果

时间:2013-03-05 12:27:00

标签: c++ debugging visual-studio-2012

我正在编写一个简单的代码,以便按顺序迭代打印二叉树,但我偶然发现了这个奇怪的调试步骤:

enter image description here

图像没有以任何方式进行photoshopped或修改,“locals”窗口显示两个指针都有不同的值,但在将它们与自身进行比较并且与NULL进行比较时,相等性返回true并且“Wat ??”打印出来,怎么样?

我错过了什么吗?

如果我将其重写为

if(pointer1 == NULL && pointer2 == NULL)
    cout << "This won't be printed";

它正常运作

2 个答案:

答案 0 :(得分:10)

等式比较运算符(operator ==)是一个与左侧相关联的二进制运算符。因此,你的条件:

pointer1 == pointer2 == NULL

变为:

(pointer1 == pointer2) == NULL,成为:

true == NULL if (pointer1 == pointer2);或

false == NULL if (pointer1 != pointer2)

由于NULL会转换为布尔值false,因此当{且仅当true时,此条件的评估结果为pointer1 != pointer2

正如您所看到的,这与以下内容截然不同:

(pointer1 == NULL && pointer2 == NULL)
当且仅当truepointer1都不是pointer2时,

评估为NULL

答案 1 :(得分:1)

它像这样工作

编译器首先检查,pointer1 == pointer2,这是假(整数值0)。现在,使用NULL检查结果0,该值也为零。因此它返回true。