Search code examples
cinteger-promotion

Will char and short be promoted to int before being demoted in assignment expressions?


After doing some research I know in arithmetic expressions char and short will be promoted to int internally. But I am still wondering whether integer promotions like that will occur in assignment internally.

(So please don't give me links only concerning other expressions. I am asking about what happens internally in ASSIGNMENT expressions)

char ch1, ch2 = -1;
ch1 = ch2;  // Q

Q: Which of the following will happen internally?

1, The value of ch1 is directly assigned to ch2. Integer promotions won't happen here.

2, The value of ch1 is first promoted to int type (8 bits→32bits), then the 32 bits value is demoted to char type, 8 bits, the final result. Integer promotions happen here.

I have found this book: C Primer Plus and in Page 174 there is:

"...When appearing in an expression, char and short, both signed and unsigned, are automatically converted to int, or if necessary, to unsigned int..."

So I think it should be 2, but I have heard someone told me it should be 1, where integer promotions don't happen.

I am really confused. Could you help me please? Thank you in advance.


Solution

  • The answer is Neither 1 nor 2.

    The value of ch2 is directly assigned to ch1. With the assignment operator, the left-hand operand is the target.

    There are no promotions; the behaviour is specified by C11 6.5.16.1/2:

    In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.

    In the previous paragraph it is defined:

    The type of an assignment expression is the type the left operand would have after lvalue conversion.

    where "lvalue conversion" means lvalue-to-rvalue conversion, which has the effect of removing const, volatile and _Atomic qualifiers for the type. (It also has an effect on array types, but that is moot here as arrays cannot appear as the left operand of an assignment).

    Your quote from "C Primer Plus" is a mistake by the book. Integer promotions do not occur in all expressions. In fact, they occur when the integer is an operand of an operator, and the definition of that operator specifies that its operands undergo the integer promotions.

    Most operators do specify that, but the assignment operator, and sizeof for example, do not. You can check the C standard's specification of each operator to see whether that operator promotes its operands.