Search code examples
javacarithmetic-expressionspostfix-operatorprefix-operator

Postfix and prefix operators in C and Java producing different results


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 )


Solution

  • 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.