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

后端 未结 4 647
盖世英雄少女心
盖世英雄少女心 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: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.

提交回复
热议问题