Why are the precedence and associativity rules different in C and Java?

130 Views Asked by At

I found that the precedence and associativity rules are different in C, C++ and Java. Have a look at this code snippet:

#include<stdio.h>
void main(){
    int k = 5;
    int x = ++k*k--*4;
    printf("%d",x);
}

The above C program gives the output as 120

Look the following Java code:

class Main
{
   public static void main(String args[])
   {
      int k = 5;
      int x = ++k*k--*4;
      System.out.println(x);
   }
}

This Java code gives 144 as output. Why this difference? I think the Java evaluation strategy is correct because it is evaluated as (pre increment)6 * 6 (post decrement) *4 = 144

Then what's wrong with C and C++? C and C++ both give 120.

1

There are 1 best solutions below

2
dbush On

In Java, left to right evaluation of most operands, including side effects, is guaranteed.

C and C++ make no such guarantee. Except for ||, &&, ?: (the ternary operator) and , (the comma operator), the evaluation order of operands is unspecified, as is any side effects that may result.

In this case:

int x = ++k*k--*4; 

The variable k is written to more than once without an intervening sequence point. This triggers undefined behavior.