-2

I thought basic arithmetic operators had same precedence in most languages. But for the following code snippet-

int a = 5;
a = --a + a++;
//print a

C copiler (GNU GCC) gives me result as 9 where as in java I get 8. What's going on? According to me it should be 8 ( 4 + 4 )

  • 1
    This is undefined behaviour is C. Changing a variable more then once in the same execution line. – Haris Aug 15 '15 at 10:24
  • The operators may have the same precedence. This doesn't mean the operands are evaluated in any particular order. – juanchopanza Aug 15 '15 at 10:25
  • 1
    More garbage. On the bright side, we haven't had this particular outflow of sewage for a while. Please stop writing crap like this and posting it on SO for it to be 'explained'. If your prof/TA wrote the crap, tell them to stop. – Martin James Aug 15 '15 at 10:56
  • Java forces left-to-right evaluation of expressions and immediate evaluation of side effects. C does not. This expression is well-defined in Java, but not in C. – John Bode Aug 15 '15 at 12:22

1 Answers1

3
a = --a + a++;

This in invokes undefined behaviour in C.

C99 §6.5: “2. Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.”

In this you change value of a twice between pervious and next sequence point ,thus result could be anything.

ameyCU
  • 16,489
  • 2
  • 26
  • 41