-6

Why is the result of JS -3?
a in JS does not seem to change with subsequent assignments

c:

int a=3;
a+=a-=a*a;

result:

a=-12;

js:

var a=3;
a+=a-=a*a;

result:

a=-3;
  • 1
    Also, this is evaluated from right to left. `a*a` is `9`. Subtracted from `a` makes it `3 - 9 === -6`, added to `a` makes it `3 - 6 === -3` – blex Jan 23 '21 at 11:31
  • 4
    Check the [precedence of the operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) and you should find the answer. But seriously... Don't write code that you can only understand with the specification alongside – Andreas Jan 23 '21 at 11:31
  • 2
    Your C code invokes undefined behaviour due to unsequenced accesses: https://godbolt.org/z/15ofoT – Siguza Jan 23 '21 at 11:38
  • @Andreas Thank you. I missed it when I copied it. – XuhuanStudio Jan 23 '21 at 11:44

1 Answers1

4

C and JavaScript have different rules to handle such expressions.

Clang (and probably also GCC and other C compilers) triggers a warning:

1.c:5:7: warning: unsequenced modification and access to 'a' [-Wunsequenced]
  a+=a-=a*a;
   ~~ ^
1 warning generated.

In plain English this says that one of the read operations will not get the initial value of a but the current value of a at the moment when that operation is executed.

The statement above is executed the same way as:

a-=a*a;
a+=a;

This is why the result in C is -12 but it could be -3 as well.


Avoid writing such expressions. Even when there is no ambiguity about how they are evaluated, they are difficult to read and understand by other developers. One of the other developers is an older version of you. The code is written once but it is read many times. Let the code be easy to read an understand.

axiac
  • 56,918
  • 8
  • 77
  • 110