Converting Arithmetic Types

Additionally, an operator for explicit type conversion is introduced.

Implicit Type Conversions

Integer promotions


 

Type hierarchy

Example

 

C++ allows you to mix arithmetic types in a single expression — in other words, the operands of an operator can belong to different types. The compiler automatically performs implicit type conversion, where a common type, which allows the operation in question to be performed, is assigned for the values of both operands. You can generally assume that the "smaller" type will be converted to the "larger" type. The assignment operator is an exception to this rule and will be discussed separately.
The result of an arithmetic operation belongs to the common type used to perform the calculation. However, comparison expressions will be bool types no matter what type of operands are involved.

Integer Promotion

Integer promotion is first performed for any expression:
  • bool, char, signed char, unsigned char, and short are converted to int
  • unsigned short is also converted to int if the int type is greater than short, and to unsigned int in all other cases.
This type conversion is performed so as to preserve the original values. The boolean value false is converted to 0 and true is converted to 1.
Thus, C++ will always use int type values or greater when performing calculations. Given a char variable c, the values of c and 'a' in the expression
Example:
c < 'a' 
will be converted to int before being compared.

Usual Arithmetic Type Conversions

If operands of different arithmetic types still occur after integer promotion, further implicit type conversions along the lines of the hierarchy on the opposite page will be necessary. In this case, the type of the operand with the highest rank in the hierarchy is applied. These type conversions and integer promotions are collectively known as usual arithmetic type conversions.
In our example, size/10 * x, the value of size is first promoted to int before an integer division size/10 is performed. The interim result 50 is then converted to double and multiplied by x.
Usual arithmetic type conversions are performed for all binary operators and the conditional operator ?: provided the operands belong to an arithmetic type, the only exceptions being the assignment operator and the logical operators && and ||.

 

Post a Comment

0 Comments