Nearby lessons

15 of 72

C - 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).

In simple words: casting is changing the label on a value — turning an integer into a float (or vice versa) so the operation you want behaves correctly.

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:

Example02
Loading editor…

Explicit Cast — (type) Operator

You can force a conversion yourself by writing the target type in brackets before the value:

Example03
Loading editor…

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:

Example04
Loading editor…

Common Mistakes

  • Expecting 2.5 from 5 / 2 — both are int, so you get 2. Use 5.0 / 2 or (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.99 gives 3, not 4.
📝 Key Takeaways
  • Integer division drops the decimal: 5 / 2 gives 2
  • Make one operand a float to get 2.5
  • Explicit cast: (float) 5 / 2

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.