Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality operators - always left-associative, will it matter?

Tags:

operators

c#

In c# Language Specification, its to be found "Except for the assignment operators, all binary operators are left-associative"

But will it make at difference for Equality operators? == and != ?

Say: bool X,Y,Z ...

return x==Y==z ... and so on?

Wont the result always be the same even if the order of x,y,z ... differs in the return statement, always return the same value? (if the init values of x,y,z is the same obviously)

(x==y)==z Equals to x==(Y==z) and for (x!=y)==z Equals to x!=(Y==z)

Right?

like image 462
Niklas Avatar asked Dec 12 '11 13:12

Niklas


1 Answers

In the C# 4.0 Language Specification, its to be found "Except for the assignment operators, all binary operators are left-associative"

FYI that line is an error. The null coalescing operator is also right-associative -- not that it matters really. See https://stackoverflow.com/a/6269773/88656 for Jon's great analysis of this issue.

Will it make at difference for equality operators == and != operating only on bools?

No. As you correctly note, operator associativity is irrelevant when dealing only with equality operators and only on bools. Though that is an interesting bit of trivia, I'm not sure why it is particularly relevant.

A number of people have answered that it makes a difference because there could be side effects in the operands. These people are wrong; this is an extremely common error. The order in which operands are evaluated has nothing whatsoever to do with the precedence or associativity of the operators. In C, for example, a conforming implementation is allowed to compute side effects in any order. If you say:

x = (A() != B()) == C();
y = D() != (E() == F());

In C then you are guaranteed that D(), E() and F() do not run before A(), B() and C(). But you are not guaranteed that side effects of B() are computed before C(). A(), B() and C() can be executed in any order in C, legally. Operator associativity, whether 'natural' or imposed by parentheses, does not impose any restriction on the order in which side effects may be computed.

The situation is somewhat improved in C#. In C# you are guaranteed that side effects of operands are observed to happen left to right regardless of the precedence or associativity of the operators. That is, if you have A() + B() * C() then you are guaranteed that A() happens before B() and that B() happens before C(), regardless of the fact that A() is involved in an addition which is lower precedence than a multiplication.

Operator precedence and associativity controls the order in which the operators run, not the order in which the operands are computed.

like image 77
Eric Lippert Avatar answered Nov 04 '22 23:11

Eric Lippert