|
|
|
|
|
|
|
instead of explicitly defining the Boolean type each time it is needed. |
|
|
|
|
|
|
|
|
As you have learned over the course of several chapters, C++ performs implicit type coercion whenever values of different data types are used in |
|
|
|
|
|
|
|
|
1. arithmetic and relational expressions |
|
|
|
|
|
|
|
|
4. return of the function value from a value-returning function |
|
|
|
|
|
|
|
|
For item 1mixed-type expressionsthe C++ compiler follows one set of rules for type coercion. For items 2, 3, and 4, the compiler follows a second set of rules. Let's examine each of these two rules. |
|
|
|
|
|
|
|
|
Type Coercion in Arithmetic and Relational Expressions |
|
|
|
|
|
|
|
|
Suppose that an arithmetic expression consists of one operator and two operandsfor example, 3.4*sum or var1/var2. If the two operands are of different data types, then one of them is temporarily promoted (or widened) to match the data type of the other. To understand exactly what promotion means, let's look at the rule for type coercion in an arithmetic expression. |
|
|
|
|
|
|
|
|
Step 1: Each char, short, or enumeration value is promoted (widened) to int. If both operands are now int, the result is an int expression. |
|
|
|
|
|
|
|
|
Step 2: If Step 1 still leaves a mixed-type expression, the following precedence of types is used: |
|
|
|
|
|
|
|
|
int, unsigned int, long, unsigned long, float, double, long double |
|
|
|
 |
|
|
|
|
The value of the operand of lower type is promoted to that of the higher type, and the result is an expression of that type. |
|
|
|
|
|
|
|
|
A simple example is the expression someFloat+2. This expression has no char, short, or enumeration values in it, so step 1 still leaves a mixed-type expression. In step 2, int is a lower type than float, so the value 2 is coerced temporarily to the float value, say, 2.0. Then the addition takes place, and the type of the entire expression is float. |
|
|
|
|
|
|
|
|
This description of type coercion also holds for relational expressions such as |
|
|
|
|
|