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 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.
Yes. The C++11 standard says in [expr.shift]/3:
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.
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.
This is legal, insofaras it doesn't cause undefined behaviour.
The behaviour of right-shift of negative values is implementation-defined . The C and C++ standards do not guarantee it to be either arithmetic or logical; although so far as I know there has never been a CPU that didn't pick one or the other.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.