0

I've read from here and there, from stackoverflow and from other websites that expression evaluation is dependent from operator precedence and associativity of the operators. The problem is that I've read the line from a certain famous website: Precedence and associativity are independent from order of evaluation. Okay, but I've read in an education site this line: The data type and the value of an expression depends on the data types of the operands and the order of evaluation of operators which is determined by the precedence and associativity of operators.

Okay, I'm confused. I know that the compiler can evaluate operators of the same precedence in a different order for optimization purpose, I think, so the behavior is undefined in which order the evaluation will happen. That means it can change the whole expression and the result would be the same if there aren't any side effects, or if there's just one side effect. Or am I wrong? If I'm right, then why do they define the associativity of operators if the order of evaluation is undefined most of the cases, except in the assignment chain, logical short-circuit operators and some other cases I think.

So in short: Is the order of evaluation dependent from the associativity. If it is then can you explain how? If it isn't dependent from the associativity then why do they define the associativity in the first place, is it just for the parsing phase, not for the evaluation phase? The only place where I've seen the associativity useful is for the ternary operator. And why doesn't associativity apply for the operator overloading, for example for the operator<< in cout where we get undefined behaviour, because the order of evaluation of the function arguments is undefined?

emilxp
  • 91
  • 1
  • 1
  • 3
  • Take an expression like `a + b*c + d*e`. Now imagine it as `operator+(a, operator+(operator*(b,c),operator*(d,e)))`. All of each's arguments must be evaluated before the call can be made, but what order that happens is unspecified. Precedence is already built into the expanded expression. – chris Feb 05 '14 at 21:09
  • From the [horse's mouth](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf): 6.5/3: "The grouping of operators and operands is indicated by the syntax.85) **Except as specified later, side effects and value computations of subexpressions are unsequenced**.86)" – John Bode Feb 05 '14 at 21:56
  • Practical example: you cannot predict the value of (INT_MAX/2)+(2/2), because the compiler might evaluate (INT_MAX+1)/2, which is an overflow. Yes, something very like this happened to me. – david.pfx Feb 06 '14 at 13:53

0 Answers0