Chapter 4. Type ConversionsIn C, operands of different types can be combined in one operation. For example, the following expressions are permissible: double dVar = 2.5; // Define dVar as a variable of type double. dVar *= 3; // Multiply dVar by an integer constant. if ( dVar < 10L ) // Compare dVar with a long-integer constant. { /* ... */ } When the operands have different types, the compiler tries to convert them to a uniform type before performing the operation. In certain cases, furthermore, you must insert type conversion instructions in your program. A type conversion yields the value of an expression in a new type, which can be either the type void (meaning that the value of the expression is discarded: see "Expressions of Type void" in Chapter 2), or a scalar typethat is, an arithmetic type or a pointer. For example, a pointer to a structure can be converted into a different pointer type. However, an actual structure value cannot be converted into a different structure type. The compiler provides implicit type conversions when operands have mismatched types, or when you call a function using an argument whose type does not match the function's corresponding parameter. Programs also perform implicit type conversion as necessary when initializing variables or otherwise assigning values to them. If the necessary conversion is not possible, the compiler issues an error message. You can also convert values from one type to another explicitly using the cast operator (see Chapter 5): (type_name) expression In the following example, the cast operator causes the division of one integer variable by another to be performed as a floating-point operation: int sum = 22, count = 5; double mean = (double)sum / count; Because the cast operator has precedence over division, the value of sum in this example is first converted to type double. The compiler must then implicitly convert the divisor, the value of count, to the same type before performing the division. You should always use the cast operator whenever there is a possibility of losing information, as in a conversion from int to unsigned int, for example. Explicit casts avoid compiler warnings, and also signpost your program's type conversions for other programmers. For example, using an explicit cast to void when you discard the return value of a function serves as a reminder that you may be disregarding the function's error indications. To illustrate the implicit type conversions that the compiler provides, however, the examples in this chapter use the cast operator only when it is strictly necessary. |