Hello everyone
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 :
a == b == c does not do what you expect it to do! It first calculates a == b, which is either true or false – or as integral value 1 or 0 – and then compares this value against c – so you can ever only get a final value of true if c compares equal to either 0 or 1, which it ever cannot in given case. To achieve the equivalence to mathematical a = b = c you need to compare one value twice against the other two, e.g. a == b && a == c
Which one of the values you chose to compare twice doesn’t matter for the final result – but you shouldn’t calculate the same value twice (at least if it’s a complex calculation); if all three values are calculated store the one to compare twice in a temporary variable; in concrete case:
unsigned tmp = 2 + 2;
// (admitted, SUCH A SIMPLE ONE would not be worth the
// effort, compiler would optimize it anyway)
std::cout << (tmp == 2*2 && tmp == pow(2,2));
Be aware, though: pow introduces floating point – while it would still produce correct results if inputs are integers you might run into rounding issues for other values (see e.g. here or search here on SO for comparing floating point values), so (apart from being overkill here anyway) you always should think twice if you really want to use it (and yes, there are valid use cases…)!