Question

I know that whenever an operator used on two operands which have different types, the results type would be the "dominant" type between the two operands.
For example, the result of
(int) + (float)
would be a float.
Another example would be:
(char) + (double) and the result is double.

That is correct for signed variables and only signed variables.

But what happens when we involve signed variables with unsigned variables?

Was it helpful?

Solution

The details are in C11, 6.3.1.8. To summarize:

  • If the unsigned type is equal-or-wider, the signed type is converted to unsigned.

  • Otherwise, if the signed type can hold all the values of the unsigned type, the unsigned type is converted to the signed type.

  • Otherwise, both are converted to the to the unsigned version corresponding to the signed type.

By "wider" I mean "has higher conversion rank".

Examples (on some particular architecture, e.g. sizeof(short) == 2 and sizeof(long) == sizeof(unsigned int) = 4):

int + unsigned int     => unsigned int  (first rule, equal rank)

long + unsigned short  => long          (second rule, long contains u. short)

long + unsigned int    => unsigned long (third rule)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top