Implicit Type Conversion: If one operand is short

2019-03-31 00:05发布

问题:

K&R states, that if either operand is an int the other operand will be converted to int. Of course, that is only after all the other rules (like long double, float, unsigned int etc.) have been followed.

By that logic, char would be converted to int, if the other operand was an int. But what if the highest integer type in an operation is a short?

Now, obviously I don't need to explicitly convert a char to a bigger integer, but I do wonder, does ANSI-C handle implicit conversion between char and short under the hood? K&R does not say anything about that.

Say, I have the following lines of code:

char x = 'x';
short y = 42;
short z = x + y;

Will x be converted to short? Or will there be no conversion to begin with at all?

Just to make it clear: I'm not asking for whether or how to convert from char to short. I just want to know what happens in regards to implicit type conversions.

回答1:

The "integer promotion" will convert both of them to int before the addition:

The following may be used in an expression wherever an int or unsigned int may be used:

— An object or expression with an integer type whose integer conversion rank is less than the rank of int and unsigned int.

[...] If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.

(ISO/IEC ISO/IEC 9899:1999 (E), §6.3.1.1)



回答2:

According to the standard , short can never be defined using less number of bits than char. Therefore, x will indeed be converted to short.