Search code examples
javascriptc++cprogramming-languagesundefined-behavior

How do languages handle side effects of compound operators?


Assume such situation:

int a = (--t)*(t-2);
int b = (t/=a)+t;

In C and C++ this is undefined behaviour, as described here: Undefined behavior and sequence points

However, how does this situation look in:

  • JavaScript,
  • Java,
  • PHP...
  • C#
  • well, any other language which has compound operators?

I'm bugfixing a Javascript -> C++ port right now in which this got unnoticed in many places. I'd like to know how other languages generally handle this... Leaving the order undefined is somehow specific to C and C++, isn't it?


Solution

  • According to the ECMA Script specification, which I believe javascript is supposed to conform to, in multiplication and addition statements, it evaluates the left hand side before evaluating the right hand side. (see 11.5 and 11.6). I think this means that the code should be equivalent to

    t = t - 1;
    int a = t * (t - 2);
    t = t / a;
    int b = t + t;
    

    However, you should not always trust the specification to be the same as the implementation!

    Your best bet in confusing cases like this is to experiment with various inputs to the ambiguous lines of code in the original operating environment, and try to determine what it is doing. Make sure to test cases that can confirm a hypothesis, and also test cases that can falsify it.

    Edit: Apparently most JavaScript implements the 3rd edition of ECMAScript, so I changed the link to that specification instead.