The integer promotion rules are defined in 6.3.1.8 Usual arithmetic conversions.
1. int16_t x, pt;
int32_t speed;
uint16_t length;
x = (speed*pt)/length;
2. x = pt + length;
Ranking means effectively the number of bits from the type as defined by CAM in limits.h
. The standards imposes for the types of lower rank in CAM to correspond types of lower rank in implementation.
For your code,
speed * pt
is multiplication between int32_t and int16_t, which means, it is transformed in
speed * (int16_t => int32_t) pt
and the result tmp1
will be int32_t
.
Next, it will continue
tmp1_int32 / length
Length will be converted from uint16_t
to int32_t
, so it will compute tmp2
so:
tmp1_int32 / (uint16_t => int32_t) length
and the result tmp2
will be of type int32_t
.
Next it will evaluate an assignment expression, left side of 16 bits and the right side of 32, so it will cut the result so:
x = (int32_t => int16_t) tmp2_int32
Your second case will be evaluated as
x = (int32_t => int16_t) ( (int16_t => int32_t) pt + (uint16_t => int32_t) length )
In case an operator has both operands with rank smaller than the rank of int, the CAM allows to add both types if the operation does not overflow and then to convert the result to integer.
In other words, it is possible to covert INT16+INT16 either in
INT16+INT16
or in
(int32_t => int16_t) ((int16_t => int32_t) INT16 + (int16_t => int32_t) INT16)
provided the addition can be done without overflow.