std::cout << (abs(b - c) < a) && a < b + c ? 1 : 0;
I want to check if given values can create triangle. I got warnings:
second operand of conditional expression has no effect [-Wunused-value]
third operand of conditional expression has no effect [-Wunused-value]
What's wrong?
Your code translates to:
((std::cout << (abs(b - c) < a)) && a < b + c) ? 1 : 0;
Firstly, operator<<
has higher operator precedence than operator&&
.
Only the value of abs(b - c) < a
will be printed and the (a < b + c ? 1 : 0)
part will be AND-ed together with the return value of std::ostream::operator bool
.
But the warning is about 1
and 0
not being assigned to anything nor having any side effects, because &&
precedes the ternary conditional (?:
).
The correct code is either:
std::cout << (abs(b - c) < a && a < b + c ? 1 : 0);
// same as std::cout << ((abs(b - c) < a && a < b + c) ? 1 : 0);
or
std::cout << (abs(b - c) < a && (a < b + c ? 1 : 0));
In fact, they're equivalent (apart that one calls operator<<
with bool
and the other with int
), no ternary operator needed:
std::cout << (abs(b - c) < a && a < b + c);