Sequence point within assignment operators

末鹿安然 提交于 2019-12-19 10:08:28

问题


Let's just take for example the specific compound assignment operator ^=. This stackoverflow page says modification of the left operand may have not been done after the evaluation of ^=, and thus making the code a ^= b ^= a ^= b undefined behaivor. But this does not seem to be the case. The standard says in 5.17 [expr.ass] that

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

There are two keypoints in this statement. 1) What does the subject assignment refers to? In my opinion, it refers just to the modification of the left operand. 2) What does value computation of the assignment expression refers to? cppreference says it refers to returning the reference to the modified object (emphasis mine).

As a conclusion, the left operand should have already been modified after the evaluation of ^=, which is a contradiction to what (most) people think. Am I missing something here?


回答1:


You link to a C question. However, this is irrelevant as C and C++ are different languages.

Also, sequence points no longer exist as of C11 and C++11; instead the relations sequenced before, unsequenced, and indeterminately sequenced exist.

In that quote:

  • the assignment means the write to the memory location of a.
  • value computation of an expression means the computation of the value of that expression. (Example - the value of 2 + 2 is 4, and the value computation is the process of determining that 4 was the value).

There are two value computations here: a ^ b, and a = (that result).

In the quoted text, for a = a ^ b, things must occur in this order:

  1. Retrieve values from a and b (in either order), and determine the memory location in which to store the result (value computation of right and left operand, respectively)

  2. Store the result in a (the assignment). The involves value computation of a ^ b, which isn't mentioned in the quote but clearly the result must be calculated before it is stored

  3. Perform value computation of the assignment expression. This means yielding up the value stored in a ready for a surrounding expression to use (value computation).

You're right that 2 and 3 seem "backwards" compared to the order you might do things on paper. But remember that in general, y is different to the value of x = y. The value of the assignment expression is the same as the value stored in x . (Example: int x; double y = (x = 6.5); - then y is 6, not 6.5). So we can do this by storing the result in a and then offering a as the result.



来源:https://stackoverflow.com/questions/29313902/sequence-point-within-assignment-operators

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