Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The output of the following program is "they are not equal", but I'd expect "they are equal" as the three compared variables (x,y, and z) are equal. Why?

#include <iostream>

int main()
{
    int y, x, z;
    y = 3;
    x = 3;
    z = 3;

    if (x == y == z)
    {
        std::cout << "they are equal
";
    }
    else
    {
        std::cout << "they are not equal
";
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
259 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is because of the way expression and types are evaluated.

Let's evaluate the leftmost ==

x == y ...

This evaluates to true. Let's rewrite the expression:

//  x == y
if (true   == z) {
    // ...
}

The true is a boolean value. A boolean value cannot be directly compared to an int. A conversion from the boolean to an integer must occur, and the result is 1 (yes, true == 1). Let's rewrite the expression to its equivalent value:

//  true
if (1    == z) {
    //    ^--- that's false
}

But z isn't equal to 1. That expression is false!

Instead, you should separate both boolean expressions:

if (x == y && y == z) {
    // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...