Nearby lessons
22 of 124C - Type Casting
Learn about type casting in C — converting a value from one data type to another. Understand the integer-division trap and how the cast operator (type) converts values explicitly.
What is Type Casting?
Type casting means converting a value from one data type to another. C does this automatically in many situations (implicit conversion), and you can also force it yourself with the cast operator (explicit conversion).
The Integer Division Trap
The most common casting problem in C is integer division. When both operands of / are integers, C performs integer division and drops the decimal part:
Explicit Cast — (type) Operator
You can force a conversion yourself by writing the target type in brackets before the value:
Implicit Conversion
When you mix types, C quietly converts the smaller type to the larger one (promotion). For example int + float becomes float + float automatically:
Common Mistakes
- Expecting 2.5 from 5 / 2 — both are int, so you get 2. Use
5.0 / 2or(float) 5 / 2. - Casting too late —
(float)(5 / 2)first divides as int (2) and then casts to 2.0. Cast before the division. - Forgetting that (int) truncates —
(int) 3.99gives 3, not 4.
- Integer division drops the decimal: 5 / 2 gives 2
- Make one operand a float to get 2.5
- Explicit cast: (float) 5 / 2