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.

+3


source to share


2 answers


Yes. The C ++ 11 standard says in [expr.shift] / 3:

The value E1 >> E2

is the E1

position shifted to the right E2

. If it E1

is of an unsigned type, or if it E1

is of a signed type and a non-negative value, the value of the result is an integral part of the quotient E1/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.

+6


source


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.

+3


source







All Articles