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

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c++ - Why comparing three variables together with == evaluates to false?

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...