Home > Net >  Integer promotions in C programming
Integer promotions in C programming

Time:05-14

In the code below which statements have integer promotions?

unchar a;
unchar b;
short c;
a = 0xFE;
b = 0xFE;
c = a b;
int d = a==b

I got the question like this in a question series. How to answer it.

Moreover,Some data types like char , short int take less number of bytes than int, these data types are automatically promoted to int or unsigned int when an operation is performed on them. This is called integer promotion. For example no arithmetic calculation happens on smaller types like char, short and enum.

CodePudding user response:

which statements have integer promotions.

unchar a;
unchar b;
short c;

These appear to be declarations, and possibly unchar is an alias for unsigned char. There are no expressions in them, so there are no integer promotions.

a = 0xFE;

0xFE is an unsuffixed hexadecimal constant whose value, 254, must fit in an int. Per C 2018 6.4.4.1 5, its type is int. a is an lvalue. As the left operand of an assignment, it is left as an lvalue and not converted to a value.

Per C 2018 6.5.16 2, the right operand is converted to the type the left operand would have after lvalue conversion, hence unsigned char. The integer promotions are not performed.

b = 0xFE;

This is the same as above.

c = a b;

For the binary operator on arithmetic operands, the usual arithmetic conversions are performed, per c 2018 6.5.6 5. For integer operations, the usual arithmetic conversions include the integer promotions. Thus the integer promotions are performed on a and on b.

Except in esoteric C implementations, int can represent all the values of unsigned char. In this case, the integer promotions convert unsigned char to int. So they convert each of a and b to int.

Then produces an int result, and, since it is the right operand of assignment, it is converted to the type c would have after lvalue conversion, short. There are no further integer promotions.

int d = a==b

This is similar to above. For arithmetic operands of ==, the usual arithmetic conversions are performed, per C 2018 6.5.9 4. These include the integer promotions on a and on b. There are no other integer promotions in this.

  •  Tags:  
  • c
  • Related