Chapter 4. Type Conversions
In 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 type—that 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access