integer promotion in c

前端 未结 2 593
生来不讨喜
生来不讨喜 2021-01-15 22:25

Let say I have a 32-bit machine.

I know during integer promotion the expressions are converted to:\\

  • int if all
2条回答
  •  无人及你
    2021-01-15 23:10

    The integer promotion rule, correctly cited C11 6.3.1.1:

    If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.

    Where "otherwise, it is converted to an unsigned int" is in practice only used in one particular special case, namely where the smaller integer type unsigned short has the same size as unsigned int. In that case it will remain unsigned.

    Apart from that special case, all small integer types will always get promoted to (signed) int regardless of their signedness.


    Assuming 32 bit int, then:

     x = (speed*pt)/length;
    

    speed is signed 32, it will not get promoted. ptr will get integer promoted to int (signed 32). The result of speed*ptr will have type int.

    length will get integer promoted to int. The division will get carried out with operands of type int and the resulting type will be int.

    The result will get converted to signed 16 as it is assigned to x (lvalue conversion during assignment).

    x = pt + length; is similar, here both operands of + will get promoted to int before addition and the result will afterwards get converted to signed 16.

提交回复
热议问题