3.3.1.1 When Should I Cast Expressions?
Expressions can be explicitly cast using the cast operator -- a type in
round brackets, for example, (int
). In all cases, conversion of one type
to another must be done with caution and only when absolutely necessary.
Consider the example:
unsigned long l;
unsigned short s;
s = l;
Here, a long
type is being assigned to an
int
type and the assignment will truncate the value in
l
. The compiler will automatically perform a type conversion from the
type of the expression on the right of the assignment operator (long
) to
the type of the value on the left of the operator (short
).This is called
an implicit type conversion. The compiler typically produces a warning concerning the
potential loss of data by the truncation.
A cast to type short
is not required and should not be
used in the above example if a long
to short
conversion
was intended. The compiler knows the types of both operands and performs the conversion
accordingly. If you did use a cast, there is the potential for mistakes if the code is
later changed. For example, if you had:
s = (short)l;
the code works the same way; but if in the future, the type of
s
is changed to a long
, for example, then you must
remember to adjust the cast, or remove it, otherwise the contents of l
will continue to be truncated by the assignment, which may not be correct. Most
importantly, the warning issued by the compiler will not be produced if the cast is in
place.
Only use a cast in situations where the types used by the compiler are not the types that you require. For example, consider the result of a division assigned to a floating-point variable:
int i, j;
float fl;
fl = i/j;
In this case, integer division is performed, then the rounded integer
result is converted to a float
format. So if i
contained
7 and j
contained 2, the division yields 3 and this is implicitly
converted to a float
type (3.0) and then assigned to fl
.
If you wanted the division to be performed in a float
format, then a cast
is necessary:
fl = (float)i/j;
(Casting either i
or j
forces the
compiler to encode a floating-point division.) The result assigned to fl
now is 3.5.
An explicit cast can suppress warnings that might otherwise have been produced. This can also be the source of many problems. The more warnings the compiler produces, the better chance you have of finding potential bugs in your code.