How is shift operator evaluated in C?

后端 未结 3 1778
清歌不尽
清歌不尽 2021-01-01 11:53

I recently noticed a (weird) behavior when I conducted operations using shift >> <<!

To explain it, let me write this small run

3条回答
  •  醉话见心
    2021-01-01 12:24

    The shift operations would do integer promotions to its operands, and in your code the resulting int is converted back to char like this:

    // first operation
    a = ((a<<7)>>7); // a = (char)((a<<7)>>7);
    
    // second operation
    b <<= 7; // b = (char) (b << 7);
    b >>= 7; // b = (char) (b >> 7);
    

    Quote from the N1570 draft (which became the standard of C11 later):

    6.5.7 Bitwise shift operators:

    1. Each of the operands shall have integer type.
    2. The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

    And it's supposed that in C99 and C90 there are similar statements.

提交回复
热议问题