Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 503
Mensu Avatar asked Dec 01 '25 15:12

Mensu


1 Answers

From the C99 standard:

6.5.16.1 Simple assignment

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 your case since both the LHS and RHS are of the same type, there is no need for any conversion.

like image 148
R Sahu Avatar answered Dec 04 '25 07:12

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!