Is it legal for static_assert that signed right shift has two's complement behavior?
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");
or the C equivalent:
_Static_assert(((-4) >> 1) == -2, "my code assumes sign-extending right shift");
I don't know the rules for constant expressions as to whether implementation-defined operations can be used as above.
I know that the opposite shifted left shift of negative numbers is undefined, regardless of the machine type.
source to share
Yes. The C ++ 11 standard says in [expr.shift] / 3:
The value
E1 >> E2
is theE1
position shifted to the rightE2
. If itE1
is of an unsigned type, or if itE1
is of a signed type and a non-negative value, the value of the result is an integral part of the quotientE1/2^E2
. If E1 is signed and has a negative value, the resulting value is implementation-defined.
And nowhere in [expr.const] / 2 does it say that such a shift or implementation-defined expressions are not constant expressions at all. Thus, you get a constant expression that has an implementation-defined meaning.
source to share
This is legal as it does not cause undefined behavior.
The behavior of right-shifting negative values ββis implementation-defined. The C and C ++ standards do not guarantee that they are either arithmetic or logical; although, as far as I know, there has never been a processor that didn't choose one or the other.
source to share