是“++ l * = m”未定义的行为? [英] Is "++l *= m" undefined behaviour?
问题描述
我开始学习C ++ 0x。我遇到了下面的表达式:
I have started studying about C++0x. I came across the follow expression somewhere:
int l = 1, m=2;
++l *= m;
我不知道第二个表达式是否具有良好定义的行为。所以我在这里问。
I have no idea whether the second expression has well defined behavior or not. So I am asking it here.
不是UB吗?
推荐答案
在上面的代码中,前缀 ++
优先于 * =
,因此首先执行。结果是 l
等于 4
。
In the code above, prefix ++
has precedence over *=
, and so gets executed first. The result is that l
equals 4
.
UPDATE:确实是未定义的行为。
UPDATE: It is indeed undefined behavior. My assumption that precedence ruled was false.
原因是 l
是<$ p $的左值和右值c $ c> * = ,以及 ++
。这两个操作不排序。因此, l
被写入(和读取)两次没有序列点(旧标准字),行为是未定义的。
The reason is that l
is both an lvalue and rvalue in *=
, and also in ++
. These two operations are not sequenced. Hence l
is written (and read) twice "without a sequence point" (old standard wording), and behavior is undefined.
作为旁注,我推测你的问题源于C ++ 0x中序列点的变化。 C ++ 0x已经将关于序列点的措辞改为之前排序,以使标准更清晰。据我所知,这不改变C ++的行为。
As a sidenote, I presume your question stems from changes regarding sequence points in C++0x. C++0x has changed wording regarding "sequence points" to "sequenced before", to make the standard clearer. To my knowledge, this does not change the behavior of C++.
更新2:事实证明,按照 N3126草稿的C ++ 0x 。 @Johannes Schaub的回答是正确的,并记录语句的排序。信用当然应该回答他的回答。
UPDATE 2: It turns out there actually is a well defined sequencing as per sections 5.17(1), 5.17(7) and 5.3.2(1) of the N3126 draft for C++0x. @Johannes Schaub's answer is correct, and documents the sequencing of the statement. Credit should of course go to his answer.
这篇关于是“++ l * = m”未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!