1.6 Type Conversions

A type conversion yields the value of an expression in a new type. Conversion can be performed only on scalar types, i. e., arithmetic types and pointers.

A type conversion always conserves the original value, if the new type is capable of representing it. Floating-point numbers may be rounded on conversion from double to float, for example.

Type conversions can be implicit—i. e., performed by the compiler automatically—or explicit, through the use of the cast operator. It is considered good programming style to use the cast operator whenever type conversions are necessary. This makes the type conversion explicit, and avoids compiler warnings.

1.6.1 Integer Promotion

Operands of the types _Bool, char, unsigned char, short, and unsigned short, as well as bit-fields, can be used in expressions wherever operands of type int or unsigned int are permissible. In such cases, integer promotion is performed on the operands: they are automatically converted to int or unsigned int. Such operands are converted to unsigned int only if the type int cannot represent all values of the original type.

Thus C always "expects" values that have at least type int. If c is a variable of type char, then its value in the expression:

 c + '0'

is promoted to int before the addition takes place.

1.6.2 Usual Arithmetic Conversions

The operands of a binary operator may have different arithmetic types. In this case, the usual arithmetic conversions are implicitly performed to cast their values in a common type. However, the usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||.

If operands still have different types after integer promotion, they are converted to the type that appears highest in the hierarchy shown in Figure 1-4. The result of the operation also has this type.

Figure 1-4. Arithmetic type promotion hierarchy

figs/Cpr_04.gif

When one complex floating type is converted to another, both the type of the real part and the type of the imaginary part are converted according to the rules applicable to the corresponding real floating types.

1.6.3 Type Conversions in Assignments and Pointers

A simple assignment may also involve different arithmetic types. In this case, the value of the right operand is always converted to the type of the left operand.

In a compound assignment, the usual arithmetic conversions are performed for the arithmetic operation. Then any further type conversion takes place as for a simple assignment.

A pointer to void can be converted to any other object pointer. An object pointer can also be converted into a pointer to void. The address it designates—its value—remains unchanged.