Type Conversion & Casting in C
Type conversion means converting one data type into another.
C supports two types:
Implicit Conversion (automatic)
Explicit Conversion (Casting) (manual)
What is Type Conversion?
Type conversion happens when a value of one data type is used in a context that requires another data type.
Example:
int x = 5.75;
Compiler converts 5.75 β 5 automatically.
Types of Type Conversion
1. Implicit Type Conversion (Automatic) 2. Explicit Type Conversion (Casting)
1. Implicit Type Conversion (Automatic)
The compiler performs this conversion itself.
Conversion Rules
- char β int β float β double
- Smaller type converts to larger type
- No data-loss if converting upward
Example β Implicit Conversion
#include <stdio.h>
int main() {
int a = 10;
float b = a; // int β float
printf("a = %d\n", a);
printf("b = %.2f\n", b);
return 0;
}
Example β Automatic Type Promotion in Expressions
#include <stdio.h>
int main() {
int a = 5;
float b = 2.5;
float result = a + b; // int β float
printf("Result = %.2f", result);
return 0;
}
2. Explicit Type Conversion (Casting)
Casting is done manually by the programmer using a cast operator:
(data_type)
Example β Explicit Casting
#include <stdio.h>
int main() {
float x = 10.75;
int y = (int)x; // casting float β int
printf("x = %.2f\n", x);
printf("y = %d\n", y);
return 0;
}
Output:
10.75 β 10 (decimal removed)
Difference Between Implicit & Explicit Conversion
Implicit (automatic): - Performed by compiler - No syntax needed - Safe when converting smaller to larger Explicit (casting): - Forced by programmer - Syntax required: (int), (float) - Risk of data loss
Example β Preventing Wrong Division
#include <stdio.h>
int main() {
int a = 5, b = 2;
float result1 = a / b; // integer division β 2
float result2 = (float)a / b; // correct float division β 2.5
printf("Without casting: %.2f\n", result1);
printf("With casting: %.2f\n", result2);
return 0;
}
Example β Casting in Expressions
#include <stdio.h>
int main() {
int x = 7, y = 3;
float div = (float)(x + y) / 2;
printf("Average = %.2f", div);
return 0;
}
Example β char to int Conversion
#include <stdio.h>
int main() {
char ch = 'A';
int ascii = (int)ch;
printf("ASCII of A = %d", ascii);
return 0;
}
Common Mistakes
- Forgetting to add parentheses in casting
- Casting after division instead of before
- Thinking casting changes original variable (it doesnβt)
Practice Questions
- What is implicit type conversion? Give two examples.
- Explain explicit type casting with syntax.
- What happens when float is cast to int?
- Write a program to convert char to ASCII number.
- Why is casting important in division?
Practice Task
Write a program to read 2 integers and print:
β’ Their average using casting
β’ Their sum without casting
β’ Their division with and without casting