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