移位操作数在C ++ 17中排序 [英] Shift operands sequenced in C++17
问题描述
我读了C ++ 17 Standard $ 8.5.7.4:
I read in the C++17 Standard $8.5.7.4:
表达式E1在表达式E2之前排序.
The expression E1 is sequenced before the expression E2.
对于移位运算符.
cppreference 规则19表示:
In a shift operator expression E1<<E2 and E1>>E2, every value
computation and side-effect of E1 is sequenced before every value
computation and side effect of E2
但是当我尝试使用gcc 7.3.0或clang 6.0.0编译以下代码时
But when I try to compile the following code with gcc 7.3.0 or clang 6.0.0
#include <iostream>
using namespace std;
int main() {
int i = 5;
cout << (i++ << i) << endl;
return 0;
}
我收到以下gcc警告:
I get the following gcc warning:
../src/Cpp_shift.cpp: In function ‘int main()’:
../src/Cpp_shift.cpp:6:12: warning: operation on ‘i’ may be undefined [-Wsequence-point]
cout << (i++ << i) << endl;
~^~
叮当警告是:
warning: unsequenced modification and access to 'i' [-Wunsequenced]
我使用以下命令进行编译:
I used the following commands to compile:
g++ -std=c++17 ../src/Cpp_shift.cpp -o Cpp_shift -Wall
clang++ -std=c++17 ../src/Cpp_shift.cpp -o Cpp_shift -Wall
在两种情况下(5 * 2 ^ 6)我都得到了预期的320
输出
I get the expected 320
as output in both cases ( 5 * 2 ^ 6 )
有人可以解释为什么我收到此警告吗?我有事吗我还阅读了与此相关的问题,但确实如此不回答我的问题.
Can someone explain why I get this warning? Did I overlook something? I also read this related question, but it does not answer my question.
所有其他变体++i << i
,i << ++i
和i << i++
会产生相同的警告.
edit: all other variants ++i << i
, i << ++i
and i << i++
result in the same warning.
edit2:(i << ++i)
对于clang(正确)导致320
,对于gcc(错误)导致384
.如果++
位于E2
,似乎gcc给出了错误的结果,(i << i++)
也给出了错误的结果.
edit2: (i << ++i)
results in 320
for clang (correct) and 384
for gcc (incorrect). It seems that gcc gives a wrong result if the ++
is at E2
, (i << i++)
also gives a wrong result.
推荐答案
标准清楚地说明了移位运算符操作数的求值顺序.
Standard is clear about the order of evaluation of the operands of the shift operator.
n4659-§8.8(p4):
n4659 - §8.8 (p4):
表达式
E1
在表达式E2
之前排序.
The expression
E1
is sequenced before the expressionE2
.
表达式i++ << i
中没有未定义的行为,定义明确.它是 Clang 和
There is no undefined behavior in the expression i++ << i
, it is well defined. It is a bug in Clang and GCC both.
这篇关于移位操作数在C ++ 17中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!