How does using a relational operator in an algebraic expression work?

119 Views Asked by At

I came across a piece of code where <= is used in an algebraic expression in C.

int x=2, y=4, z=5, m=10;
m+= x * y + z++ <=m+3;
printf("%d, %d", m,z);

I've never seen the use of a relational operator in this manner and wondered how the output of this is being computed. The output that I receive when running this is 11, 6. In what way does <= work here?

2

There are 2 best solutions below

0
Vlad from Moscow On

This statement

m+= x * y + z++ <=m+3;

may be rewritten like

m += (x * y + z++ ) <= ( m+3 );

due to precedence of operators.

Taking into account these declarations

int x=2, y=4, z=5, m=10;

the operand (x * y + z++ ) of the relational operator <= is equal to 2 * 4 + 5 that is equal to 13 (pay attention to that the value of the postfix increment operator is the value of its operand before incrementing) , m + 3 is also equal to 13. So the relational operator yields 1.

And in fact you have

m += 1;

From the C Standard (6.5.8 Relational operators)

6 Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.107) The result has type int.

As a result m will be equal to 11 and z due to the postfix increment operator after this statement will be equal to 6.

0
John Bode On

The result of a relational expression is 0 (if the expression is false) or 1 (if the expression is true).

So

m += x * y + z++ <= m + 3;

will add 1 to m if the result of x * y + z++ is less than or equal to the result of m + 3, 0 otherwise.

Based on the initial values of x, y, z, and m, the relational expression should evaluate to true.

Never, ever write code like this. This is bad. Yes, I'm guilty of using relational and logical expressions in a similar manner in assignments, but not with so many side effects.