Does bit shift automatically promote chars to int?

2019-02-26 07:58发布

问题:

This question already has an answer here:

  • Bitshift and integer promotion? 2 answers

I read somewhere that bitwise shift automatically turns the operand into an int. But I'm not sure if that statement should be qualified with "if the operands are of unequal type."

char one = 1, bitsInType = 8;
one << (bitsInType - one);

Does the default result of the second line result in an int or char?

回答1:

The result type is int in normal C implementations.1

Per C 2011 (N1570) 6.5.7, “The integer promotions are performed on each of the operands. The type of the result is the that of the promoted left operand.”

Per 6.3.1.1 2, the integer promotions are, for objects or expressions of integer type with rank less than or equal to the rank of int and unsigned int: “If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int.”


1There has been discussion elsewhere in Stack Overflow from which it seems that a bizarre C implementation could have a char of the same width as int, which leads to some unusual behavior.



回答2:

C11 Standard, section 6.5.7 Bitwise shift operators, states:

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand.

This means that the values are converted to int and then the operation is performed; the result of your expression is int.