Why is JavaScript's post-increment operator different from C and Perl?

后端 未结 4 607
盖世英雄少女心
盖世英雄少女心 2021-01-05 17:39

I\'m studying for an exam on JavaScript at the moment. I\'ve also got a little knowledge of C and Perl so I\'m familiar with prefix and postfix operators in all three langua

相关标签:
4条回答
  • 2021-01-05 18:17

    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
    
    0 讨论(0)
  • 2021-01-05 18:24

    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
    
    0 讨论(0)
  • 2021-01-05 18:33

    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.

    0 讨论(0)
  • 2021-01-05 18:36

    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.

    0 讨论(0)
提交回复
热议问题