Arithmetic Conversions
Many binary operators (discussed in Expressions with Binary Operators) cause conversions of operands and yield results the same way. The way these operators cause conversions is called "usual arithmetic conversions." Arithmetic conversions of operands of different native types are performed as shown in the following table. Typedef types behave according to their underlying native types.
Conditions for Type Conversion
Conditions Met |
Conversion |
---|---|
Either operand is of type long double. |
Other operand is converted to type long double. |
Preceding condition not met and either operand is of type double. |
Other operand is converted to type double. |
Preceding conditions not met and either operand is of type float. |
Other operand is converted to type float. |
Preceding conditions not met (none of the operands are of floating types). |
Integral promotions are performed on the operands as follows:
|
The following code illustrates the conversion rules described in the table:
// arithmetic_conversions.cpp
double dVal;
float fVal;
int iVal;
unsigned long ulVal;
int main() {
// iVal converted to unsigned long
// result of multiplication converted to double
dVal = iVal * ulVal;
// ulVal converted to float
// result of addition converted to double
dVal = ulVal + fVal;
}
The first statement in the preceding example shows multiplication of two integral types, iVal and ulVal. The condition met is that neither operand is of floating type and one operand is of type unsigned int. Therefore, the other operand, iVal, is converted to type unsigned int. The result is assigned to dVal. The condition met is that one operand is of type double; therefore, the unsigned int result of the multiplication is converted to type double.
The second statement in the preceding example shows addition of a float and an integral type, fVal and ulVal. The ulVal variable is converted to type float (third condition in the table). The result of the addition is converted to type double (second condition in the table) and assigned to dVal.