Node:The cast operator, Next:Storage classes, Previous:Initialization, Up:Variables and declarations
An operator is a symbol or string of C characters used as a
function. One very valuable operator in C is the cast operator,
which converts one type into another. Its general form is as follows:
(type) variable
For example, floating point and integer types can be interconverted:
float exact_length; int rough_length; exact_length = 3.37; rough_length = (int) exact_length;
In the example above, the cast operator rounds the number down when converting it from a float to an integer, because an integer number cannot represent the fractional part after the decimal point. Note that C always truncates, or rounds down, a number when converting it to an integer. For example, both 3.1 and 3.9 are truncated to 3 when C is converting them to integer values.
The cast operator works the other way around, too:
float exact_length; int rough_length; rough_length = 12; exact_length = (float) rough_length;
In converting large integers to floating point numbers, you
may lose some precision, since the float
type guarantees only 6
significant digits, and the double
type guarantees only 10.
It does not always make sense to convert types. (See Data structures, for examples of types that do not convert to other types well.)