Pre & post increment operator behavior in C, C++, Java, & C#

This question already has an answer here:

  • Why are these constructs (using ++) undefined behavior in C? 13 answers
  • Undefined behavior and sequence points 4 answers
  • How are java increment statements evaluated in complex expressions 1 answer
  • C# Pre- & Post Increment confusions 6 answers

  • Java and C# evaluate expressions from left to right, and the side-effects are visible immediately.

    In C++, the order of evaluation of subexpressions is unspecified, and modifying the same object twice without an intervening sequence point is undefined behavior.


    I don't have the time to write up a detailed description of the differences between C++, C, C# and Java. I will merely say that the C# behaviour of the pre and post increment operators is fully specified (in single-threaded scenarios; if you want to know about its atomicity, guarantees about observations of read and write orders in multi-processor weak memory models and so on, you're on your own to do that research.) It is not fully specified in C and C++; a compiler has broad lattitude to do whatever it pleases with re-ordering side effects. I have never used Java so I'm not going to hazard a guess as to what Java does.

    For more information on what C# does you should read the C# specification. For a short take on it, read my answer to this question:

    What is the difference between i++ and ++i?

    For an even shorter take:

    Subexpressions in a C# expression are logically grouped by precedence and associativity, and then evaluated from left to right regardless. (So for example, A() + B() * C() evaluates A(), then B(), then C(). The fact that the multiplication "comes before" the addition is irrelevant; the subexpressions are always evaluated left to right.)

    If the evaluation of a subexpression causes a side effect because of a pre or post increment subexpression then the side effect happens immediately before the result is produced.


    In C++, this is undefined behaviour, so any answer would be correct. See Undefined behavior and sequence points for further details.

    Not sure about other languages, but I would expect this code to be incorrect there, too.

    EDIT:
    See Eric Lippert's answer about C#. He disproves my assumption about C#'s behaviour.

    链接地址: http://www.djcxy.com/p/73224.html

    上一篇: 运算符优先级,哪个结果是正确的?

    下一篇: 在C,C ++,Java和C#中增加和增加运算符行为