|
|
|
|
|
|
|
then someInt can hold only integer values, and someFloat can hold only floating point values. The assignment statement |
|
|
|
|
|
|
|
|
may seem to store the integer value 12 into someFloat, but this is not true. The computer refuses to store anything other than a float value into someFloat. The compiler inserts extra machine language instructions that first convert 12 into 12.0 and then store 12.0 into someFloat. This implicit (automatic) conversion of a value from one data type to another is known as type coercion. |
|
|
|
|
|
|
|
|
also causes type coercion. When a floating point value is assigned to an int variable, the fractional part is truncated (cut off). As a result, someInt is assigned the value 4. |
|
|
|
|
|
|
|
|
With both of the assignment statements above, the program would be less confusing for someone to read if we avoided mixing data types: |
|
|
|
|
|
|
|
|
someFloat = 12.0;
someInt = 4; |
|
|
|
|
|
|
|
|
More often, it is not just constants but entire expressions that are involved in type coercion. Both of the assignments |
|
|
|
|
|
|
|
|
someFloat = 3 * someInt + 2;
someInt = 5.2 / someFloat - anotherFloat; |
|
|
|
|
|
|
|
|
lead to type coercion. Storing the result of an int expression into a float variable doesn't cause loss of information; a whole number such as 24 can be represented in floating point form as 24.0. However, storing the result of a floating point expression into an int variable can cause loss of information because the fractional part is truncated. It is easy to overlook the assignment of a floating point expression to an int variable when we try to discover why our program is producing the wrong answers. |
|
|
|
|
|
|
|
|
To make our programs as clear (and error-free) as possible, we can use explicit type casting (or type conversion). A C++ cast operation consists of a data type name and then, within parentheses, the expression to be converted: |
|
|
|
|
|