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:

  • If either operand is of type unsigned long, the other operand is converted to type unsigned long.

  • If preceding condition not met, and if either operand is of type long and the other of type unsigned int, both operands are converted to type unsigned long.

  • If the preceding two conditions are not met, and if either operand is of type long, the other operand is converted to type long.

  • If the preceding three conditions are not met, and if either operand is of type unsigned int, the other operand is converted to type unsigned int.

  • If none of the preceding conditions are met, both operands are converted to type int.

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.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft