Implicit type conversion: if one operand is short and the other is char, will char be converted to short?

K & R indicates that if either operand is int , then the other operand will be converted to int . Of course, this is only after all other rules are observed (for example, long double , float , unsigned int , etc.).

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

Now, obviously, I don’t need to explicitly convert char to a larger integer, but I really wonder if ANSI-C handles the implicit conversion between char and short under the hood? K & R says nothing about this.

Let's say I have the following lines of code:

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

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

Just to make it clear: I am not asking if I need to convert from char to short or how. I just want to know what happens with respect to implicit type conversions.

+4
source share
2 answers

The "whole promotion" converts both of them to int before adding:

The following expressions can be used in an expression: int or unsigned int can:

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

[...] If int can represent all values ​​of the original type, the value is converted to int; otherwise, it will be converted to unsigned int. They are called stock integers.

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

+5
source

According to the standard, short never be determined using fewer bits than char . Therefore, x will indeed be converted to short .

-2
source

All Articles