Type Casting
Type casting means converting a variable from one data type to another. It is useful when you want to perform operations between different types or control how data is stored and used.
Think of it like converting currencies - you might have dollars but need euros for a transaction.
In C, there are two types of type casting:
1. Implicit Type Casting (Automatic)
This happens automatically when the compiler converts one data type to another without you explicitly asking for it. It's like your phone automatically adjusting the screen brightness!
#include <stdio.h>
int main() {
int num = 10;
float result = num; // int automatically converted to float
printf("Integer: %d\n", num);
printf("Float: %.2f\n", result);
return 0;
}
Output:
Integer: 10
Float: 10.00
2. Explicit Type Casting (Manual)
This is when you manually tell the compiler to convert one type to another using the cast operator.
Syntax
(target_type) variable_name
Example
#include <stdio.h>
int main() {
float pi = 3.14159;
int whole_number = (int) pi; // Explicit casting
printf("Original float: %.5f\n", pi);
printf("Casted to int: %d\n", whole_number);
return 0;
}
Output:
Original float: 3.14159
Casted to int: 3
Common Type Casting Scenarios
Integer Division Problem
#include <stdio.h>
int main() {
int a = 7, b = 2;
// Without casting - integer division
printf("7/2 = %d\n", a/b);
// With casting - float division
printf("7/2 = %.2f\n", (float)a/b);
return 0;
}
Output:
7/2 = 3
7/2 = 3.50
Character to ASCII and Vice Versa
#include <stdio.h>
int main() {
char letter = 'A';
int ascii_value = (int) letter;
printf("Character: %c\n", letter);
printf("ASCII value: %d\n", ascii_value);
// Converting back
char converted_back = (char) ascii_value;
printf("Back to character: %c\n", converted_back);
return 0;
}
Output:
Character: A
ASCII value: 65
Back to character: A
Type Casting Hierarchy
When mixing different data types, C follows a hierarchy for automatic conversion:
| Data Type | Size | Priority |
|---|---|---|
long double | Largest | Highest |
double | Large | High |
float | Medium | Medium |
long | Medium | Medium |
int | Small | Low |
char | Smallest | Lowest |
⚠️ Important Notes
-
Data Loss: When casting from a larger type to a smaller type, you might lose data!
float big_number = 1234.56; int small_number = (int) big_number; // Loses decimal part: 1234 -
Overflow: Be careful when casting to smaller types:
int large = 300; char small = (char) large; // Might cause unexpected results! -
Precision: Converting from
doubletofloatmight lose precision.
Type casting is a powerful tool, but like any tool, use it wisely! Always consider what data you might lose in the conversion process.