Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does operator associativity matter?

Most programming languages have a table of precedence and associativity for binary operators. Associativity matters in some cases e.g. (a - b) - c != a - (b - c).

However, for an associative operator like && it would seem not to matter, yet most languages list this as left associative.

Are there any situations where there is actually a difference between (a && b) && c and a && (b && c)?

like image 927
rwallace Avatar asked Nov 17 '13 10:11

rwallace


1 Answers

I can't believe there are so many wrong (deleted) answers... maybe I should answer this.

First of all, precedence != associativity != evaluation order.

Now that we have that out of the way: associativity matters in some cases.
For a + b + c, it matters when a, b, and c are floating-point numbers instead of integers, because rounding errors will accumulate differently depending on how the terms are grouped.

For the particular case of && and ||, it doesn't matter as long as they aren't overloaded (which is possible only in C++, not C), but the language still defines one just for consistency -- and so that the "tree" representation of the code (based on the grammar) is unique. That also works out to the benefit of C++ since now the meaning of overloaded && and || isn't ambiguous.

like image 139
user541686 Avatar answered Sep 19 '22 01:09

user541686