Why is JavaScript's postfix notation different from C and Perl?

て烟熏妆下的殇ゞ 提交于 2019-11-30 20:39:19

Expanding the statement

x += x--;

to the more verbose JS code

x = x + (function(){ var tmp = x; x = x - 1; return tmp; })();

the result makes perfect sense, as it will evaluate to

x = 10 + (function(){ var tmp = 10; x = 10 - 1; return tmp; })();

which is 20. Keep in mind that JS evaluates expressions left-to-right, including compound assignments, ie the value of x is cached before executing x--.


You could also think of it this way: Assuming left-to-right evaluation order, JS parses the assignment as

x := x + x--

whereas Perl will use

x := x-- + x

I don't see any convincing arguments for or against either choice, so it's just bad luck that different languages behave differently.

In C/C++, every variable can only be changed once in every statement (I think the exact terminology is: only once between two code points, but I'm not sure).

If you write

x += x--;

you are changing the value of x twice:

  • you are decrementing x using the postfix -- operator
  • you are setting the value of x using the assignment

Although you can write this and the compiler won't complain about it (not sure, you may want to check the different warning levels), the outcome is undefined and can be different in every compiler.

Basically, the value of x is decemented after assignment. This example might make it clearer (run in Firebug console)

var x = y =10;    
x += y--;        
console.log(x , y); // outputs 20 9

In C, the line

x += x--;

is undefined behaviour. It seems like your particular compiler is treating it like:

oldx = x--;
x = x + oldx

However, the ECMAScript specification does specify op= - and it gets the value of the left-hand-side before evaluating the right-hand-side.

So it would be equivalent to:

oldx = x--;
x = oldx + oldx
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!