Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: second/third operand of conditional has no effect [-Wunused-value]

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?

like image 536
Wobbly Avatar asked Feb 28 '16 16:02

Wobbly


People also ask

Why don't we use parentheses in conditional results?

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);

What is the operator precedence for ternary conditional operator?

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.

Is the direct assignment operator equivalent to the ternary conditional operator?

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.


1 Answers

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);
like image 104
LogicStuff Avatar answered Oct 07 '22 12:10

LogicStuff