Casts
- Often, it is useful to convert between int and float
variables. For example, it is natural to want the result of dividing two
ints to be a float. The C language allows you to do this
via casts.
- To cast an expression to type int, prefix it with the string
(int). To cast an expression to type float, prefix it
with (float). Casting has higher priority than binary operators
like + but the same priority as unary operators like - or ++, so
(float) -35 / 47.3 casts -35 to a float, then performs
the division.
- Casting an int to a float is straight forward and
does what you expect. Casting a float to an int is
problematic in that
- It may cause overflow (floats can be much bigger than
ints) and
- What to do with the fractional part?
In C, int casts can cause overflow errors and for positive
floats, the fractional part is truncated down. Negative
floats may be truncated up or down, depending on your compiler
and computer.
- Casts are explicit type conversions. The C compiler also
sometimes performs implicit type conversions in at least two cases:
- When assigning a floating point expression to an int variable or
assigning an integer expression to a float, the C compiler will
cast the expression to the same type as the variable being assigned to.
- When one operand of a binary operator is an int expression and
the other is a float expression (like in 3 + 7.2),
the int expression is cast to a float.
Next Slide