Search code examples
c++typesoperatorsequality

Equality in C++


I am still learning the fundamentals of programming through C++ and was trying some applications on C++ operators, but it seems there are things about them that I still don't understand.

I tried writing the following line to test the possibility of using equal to (==) as a ternary operator:

cout << "(2+2 == 2*2 == pow(2, 2)) == " << (2+2 == 2*2 == pow(2, 2)) << endl;

The output was 0

So, I suspected that this might be because the return value of pow(2,2) is a double while that of the first two operands is an integer and thus I tried the following:

cout << "(2+2 == 2*2 == int(pow(2, 2))) == " << (2+2 == 2*2 == int(pow(2, 2))) << endl;
cout << "(double(2+2) == double(2*2) == pow(2, 2)) == " << (double(2+2) == double(2*2) == pow(2,2)) << "\n\n";

The output for both lines of code was also 0.

I have also tried the use of parentheses to reduce the number of operands but ended up with the same output.


Solution

  • Because comparison with == have left-to-right associativity, the expression

    2+2 == 2*2 == pow(2, 2)
    

    is really equal to

    (2+2 == 2*2) == pow(2, 2)
    

    That means you will be comparing the result of 2+2 == 2*2, with the result of pow(2, 2).

    Because 2+2 is equal to 2*2 the result of the first comparison will be true. This is then implicitly converted to the value 1 which is then compared to the result of the pow(2,2) call.

    And 1 == pow(2,2) is false. Which is then displayed as its numeric value equivalent of 0.


    And some nitpicking: A three-way comparison isn't really a three-way comparison, as shown above it's really two separate comparisons. So this is not a "ternary operator".

    C++ really only have one ternary operator, and that's the conditional operator ?:.