Nearby lessons

22 of 124

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
CCode Cell
1#include <stdio.h>
2void main() {
3 printf("%d\n", 5 / 2); // 2 - decimal dropped
4 printf("%.2f\n", 5.0 / 2); // 2.50 - float division
5 printf("%.2f\n", 5 / 2.0); // 2.50
6}
Output

2
2.50
2.50
      

Explicit Cast — (type) Operator

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

Example03
CCode Cell
1#include <stdio.h>
2void main() {
3 int a = 5, b = 2;
4 float result;
5 result = (float) a / b; // cast a to float first
6 printf("%.2f\n", result); // 2.50
7 
8 float pi = 3.99;
9 int rounded = (int) pi; // truncates to 3
10 printf("%d\n", rounded); // 3
11}
Output
2.50
3

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
CCode Cell
1#include <stdio.h>
2void main() {
3 int a = 10;
4 float b = 2.5;
5 printf("%.2f\n", a + b); // 12.50 - a promoted to float
6 printf("%.2f\n", a / 4.0); // 2.50
7}
Output

12.50
2.50
      

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