Reputation: 767
Assume we have an assignment using variables of the following types:
uint64 = uint16 + uint16 + uint32 + uint64
Assume we know that the resulting r-value fits inside a uint64 as long as all the work is done using uint64's.
Will the compiler implicitly promote the two uint16's and the uint32 to uint64's BEFORE doing any calculations following standard C rules?
i.e.
1.) uint64 = uint16 + uint16 + uint32 + uint64
2.) uint64 = uint64 + uint64 + uint64 + uint64
Specifically by applying the second statement in the following snippet:
If both operands have the same type, then no further conversion is needed.
Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
Or does that rule apply to only the immediate lhs and rhs of the arithmetic expression such that adding the two uint16's might be computed first where there types would not be promoted until the result was known and then it would be promoted to uint32, then this result promoted to uint64, etc...
i.e.
1.) uint64 = uint16 + uint16 + uint32 + uint64
2.) uint64 = (((uint16 + uint16) + uint32) + uint64)
3.) uint64 = ((uint32 + uint32) + uint64)
4.) uint64 = (uint64 + uint64)
Please point me to any C standard rules as well that might clear this up for me.
Upvotes: 1
Views: 363
Reputation: 145899
The rule applies to the intermediate result:
uint16 + uint16 + uint32 + uint64
is equivalent to
((uint16 + uint16) + uint32) + uint64
and the usual arithmetic conversions are performed on both sides of the +
operator.
(C99, 6.5.6 Additive operators p4) "If both operands have arithmetic type, the usual arithmetic conversions are performed on them."
Note that assuming 32-bit
int
, this is actually the same as:
(uint64) ((unsigned int) ((int) uint16 + (int) uint16) + uint32) + uint64
uint16
is promoted to int
not to unsigned int
, and then the result is converted to unsigned int
because of uint32
.
Upvotes: 3