Prefix operator difference in C++ and C#
This question already has an answer here:
It's undefined behaviour
in C++. You are trying to modify value more than one time without sequence points
(per C++98/03 standards).
About C++11
The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.
Examples:
i = v[i++]; // the behavior is undefined
i = i++ + 1; // the behavior is undefined
在C ++中, int b = ++a + ++a
是未定义的行为,因此您可以预期任何结果。
C# and C++ are different languages, with different semantics.
C# decides to first execute first one ++a, then the other ++a and finally the addition of these two expressions, hence the result is 5.
In C++ you have undefined behaviour. The result could be 2, 3, 4, 5, 6, 34500 or any other. Another possible outcome is Matthew Watson drinking all the beer in his fridge. Anything can happen, actually.
It doesn't make sense, in general, to expect the same behaviour from two different languages. Each one follows its own rules.
Note: See this question Pre & post increment operator behavior in C, C++, Java, & C# for further cross-language discussion.
链接地址: http://www.djcxy.com/p/73230.html上一篇: 序列点与运算符优先级
下一篇: C ++和C#中的前缀运算符差异