对static_assert而言,带符号的右移具有二进制补码行为合法吗? [英] Is it legal to static_assert that signed shift right has two's-complement behavior?
问题描述
在C11,C ++ 11和C ++ 14中执行以下操作合法吗?
Is it legal to do the following in C11, C++11 and C++14?
static_assert(((-4) >> 1) == -2, "my code assumes sign-extending right shift");
或C等效项:
_Static_assert(((-4) >> 1) == -2, "my code assumes sign-extending right shift");
关于您是否可以使用上述实现定义的操作,我不知道常量表达式的规则.
I don't know the rules for constant-expressions regarding whether you can use implementation-defined operations like the above.
我知道,无论机器类型如何,都没有定义相反的负号左移符号.
I'm aware that the opposite, signed shift left of negative numbers, is undefined regardless of machine type.
推荐答案
是.C ++ 11标准在[expr.shift]/3中表示:
Yes. The C++11 standard says in [expr.shift]/3:
E1>>的值;E2
是E1
右移的E2
位位置.如果E1
具有未签名的类型,或者E1
具有签名的类型且非负的类型值,结果的值是E1/2 ^ E2
.如果E1具有带符号的类型和负值,则结果值是实现定义的.
The value of
E1 >> E2
isE1
right-shiftedE2
bit positions. IfE1
has an unsigned type or ifE1
has a signed type and a non-negative value, the value of the result is the integral part of the quotient ofE1/2^E2
. If E1 has a signed type and a negative value, the resulting value is implementation-defined.
在[expr.const]/2中,没有任何地方说这样的移位或带有实现定义的值的表达式通常不是常量表达式.这样,您将获得一个具有实现定义的值的常量表达式.
And nowhere in [expr.const]/2 it is said that such a shift, or expressions with implementation-defined values in general, are not constant expressions. You will thus get a constant expression that has an implementation-defined value.
这篇关于对static_assert而言,带符号的右移具有二进制补码行为合法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!