Many binary operators (discussed in Expressions with Binary Operators in Chapter 4) 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 types are performed as shown in Table 3.1.
Table 3.1 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 Table 3.1:
float fVal;
double dVal;
int iVal;
unsigned long ulVal;
dVal = iVal * ulVal; // iVal converted to unsigned long;
// result of multiplication converted to double.
dVal = ulVal + fVal; // ulVal converted to float;
// result of addition converted to double.
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 Table 3.1). The result of the addition is converted to type double (second condition in Table 3.1) and assigned to dVal
.