Advertisement

Type Casting

C Language Variables & Data Types 📅 May 2026 ⏱ 2 min read 🆓 Free

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
ConversionWhat HappensExample
int → floatExact, adds decimal part5 → 5.0
float → intTRUNCATES (not rounds) decimal3.9 → 3
int → charUses ASCII table65 → A
char → intGets ASCII value'A' → 65
int → doubleExact, more precision7 → 7.0
⚠ Warning: float to int is TRUNCATION not ROUNDING! 3.9 becomes 3, not 4. To round properly: (int)(x + 0.5)
Advertisement
← Back to C Language Index