|
|
|
|
|
|
|
You have seen that C++ is very liberal about letting the programmer mix data types in expressions, in assignment operations, in parameter passage, and in returning a function value. However, implicit type coercion takes place when values of different data types are mixed together. Instead of relying on implicit type coercion in a statement like |
|
|
|
|
|
|
|
|
we have recommended using an explicit type cast to show that the type conversion is intentional: |
|
|
|
 |
|
|
|
|
In C++, the cast operation comes in two forms: |
|
|
|
|
|
|
|
|
intVar = int(floatVar); // Functional notation
intVar = (int) floatVar; // Prefix notation-parentheses required |
|
|
|
|
|
|
|
|
The first form is called functional notation because it looks like a function call. It isn't really a function call (there is no user-defined or predefined subprogram named int), but it has the syntax and visual appearance of a function call. The second form, prefix notation, doesn't look like any familiar language feature in C++. In this notation, the parentheses surround the name of the data type instead of the expression being converted. Prefix notation is the only form available in the C language; C++ added the functional notation. |
|
|
|
|
|
|
|
|
Although most C++ programmers use the functional notation for the cast operation, there is one restriction on its use. The data type name must be a single identifier. If the type name consists of more than one identifier, you must use prefix notation. For example, |
|
|
|
|
|
|
|
|
myVar = unsigned int(someFloat); // No
myVar = (unsigned int) someFloat; // Yes |
|
|
|
|
|
|
|
|
The sizeof operator is a unary operator that yields the size, in bytes, of its operand. The operand can be a variable name, as in |
|
|
|
|
|