Can a C compiler implement a signed right shift unreasonably?

The header field is not long enough to get a detailed question, so for the record, my actual question defines "unreasonably" in a certain way:

Is it legal 1 to implement C, does the shift operator have arithmetic right, which returns different results, over time, for identical values ​​of the arguments? That is, must >>be a true function ?

Imagine that you wanted to write portable code using shift-shift >>for signed values ​​in C. Unfortunately, for you, the most efficient implementation of some critical part of your algorithm is faster when the signed right shifts fill the sign bit (i.e. they are arithmetic shifts to the right). Now, since this behavior is defined in the implementation , you are disgusting if you want to write portable code that uses it.

Just reading the compiler documentation (which it should provide in the standard, but may or may not be easily accessible or even exists) is excellent if you know all the compilers that you will work on and will ever work on, but since it is often impossible, you can find a way to make it portable.

One way I thought was to simply check the compiler's behavior at runtime: it seems to implement an arithmetic shift to the right 2 uses an optimized algorithm, but if you don't use a reserve, rely on it. Of course, just checking that it is (short)0xFF00 >> 4 == 0xFFF0not enough to say , because it does not exclude that the values chareither intwork differently or even the strange case when it fills in some sums or shift values, but not for others 3 .

, , , . 8- char, 2 8 LHS 2 3 RHS 2 11 short (, int16_t, ) 2 20 4. 32- 2 37 , . 64- .

, , >> . : , ? (short)0xFF00 >> 4 0xFFF0 , 0x0FF0 ( ) ?

, , -, , , big.LITTLE, CPU VM- , Intel AMD, ( ) .


1 "" , C, , .

2 I.e., .

3 , : x86 ( -) 1, , ARM , , , .

4 , , . , 1 ~ 1 ~ 1 .

+4
2

, , >> . : , ? (short)0xFF00 >> 4 0xFFF0 , 0x0FF0 ( ) ?

() . , . , , .

, , .

, , , , . , .

- , . , - , - LHS. , , -, () () , , () .

+3

, . , , , , , , . , , - (, , ), .

, " ". , , , , , , , , " , 7" .

, , , - . , -1 → 1 == - 1, , , . - , - , .

+3

Source: https://habr.com/ru/post/1669409/


All Articles