0

This is a very old question, however, today I read on this and the article emphasizes that: "It is important to note that there is no specified precedence for the operation of changing a variable into a value". Here is an example given in the article to demonstrate the claim:

float x, result;
x = 1;
result = x / ++x;

"Depending on which compiler you are using, the variable result can either be 1.0 or 0.5" -->> I don't understand clearly this. Any comments?

duong_dajgja
  • 4,196
  • 1
  • 38
  • 65
  • 1
    It's nothing to do with operator precedence, but with sequencing. The two uses of `x`, one of which modifies it, aren't sequenced. That gives undefined behaviour, so anything might happen. – Mike Seymour Mar 31 '15 at 13:38
  • 1
    What that page meant to say was that operator precedence does not affect *order of evaluation*; that is, given an expression like `a + b * c`, the subexpressions `a`, `b`, and `c` may be evaluated *in any order*. `b * c` must be evaluated before the result can be added to `a`, but that doesn't mean `b` and `c` must be evaluted before `a`. This is why expressions like `x / ++x` are problematic, because it's not guaranteed that `x` will be evaluated before `++x` or vice versa. Also, it's not guaranteed that the *side effect* of the `++` operator will be applied immediately after evaluation. – John Bode Mar 31 '15 at 15:21

0 Answers0