Type Casting in C
Type casting converts a value from one data type to another. C does some conversions automatically (implicit) and you can force others (explicit).
Implicit (Automatic) Type Conversion
c
#include <stdio.h>
int main() {
int i = 10;
float f = i; // int automatically becomes float
printf("int i = %d\n", i);
printf("float f = %.1f\n", f); // 10.0
// THE CLASSIC MISTAKE — integer division
int a = 7, b = 2;
printf("\n7 / 2 (int) = %d\n", a / b); // 3 NOT 3.5!
printf("7.0 / 2 = %.1f\n", 7.0 / b); // 3.5
printf("7 / 2.0 = %.1f\n", a / 2.0); // 3.5
return 0;
}▶ Output
int i = 10 float f = 10.0 7 / 2 (int) = 3 7.0 / 2 = 3.5 7 / 2.0 = 3.5
Explicit Type Casting — Force the Conversion
c
#include <stdio.h>
int main() {
// float → int: decimal part is TRUNCATED (not rounded)
double pi = 3.99999;
int x = (int) pi; // x = 3, NOT 4!
printf("pi = %lf\n", pi); // 3.999990
printf("x = %d\n", x); // 3 (decimal LOST)
// Correct average calculation
int total = 17, count = 5;
float avg = (float) total / count; // cast first!
printf("Avg = %.2f\n", avg); // 3.40
// char ↔ int conversion (ASCII)
char ch = 'A';
printf("'A' ASCII = %d\n", (int) ch); // 65
printf("66 as char = %c\n", (char) 66); // B
return 0;
}▶ Output
pi = 3.999990 x = 3 Avg = 3.40 'A' ASCII = 65 66 as char = B
| Conversion | What Happens | Example |
|---|---|---|
| int → float | Exact, adds decimal part | 5 → 5.0 |
| float → int | TRUNCATES (not rounds) decimal | 3.9 → 3 |
| int → char | Uses ASCII table | 65 → A |
| char → int | Gets ASCII value | 'A' → 65 |
| int → double | Exact, more precision | 7 → 7.0 |
⚠ Warning: float to int is TRUNCATION not ROUNDING! 3.9 becomes 3, not 4. To round properly:
(int)(x + 0.5)