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?
It may be a historical reason: in C the conditional result was not lvalue, therefore assigning something to it had no sense, and allowing assignment to be accepted without parentheses might seem smart at that time. Show activity on this post. 1 ? (j) : (k = 1);
The key is that the two operands of the ternary conditional operator can be expressions, so operator precedence isn't relevant here. It's simply that the second operand is the assignment expression k = 1. Show activity on this post.
Since the direct assignment operator has less precedence than the ternary conditional operator, I was expecting lines commented as first and second to be equivalent. But alas it is not the case. I tried this with g++ --version (Ubuntu 4.4.3-4ubuntu5) 4.4.3 Show activity on this post.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With