Type Conversion in C
In C, type conversion, also called type casting, means converting one data type into another. It is used when we want to perform operations between different data types or store one type of value in a variable of another type.
For example, when we divide two integers, the result is normally an integer. But if we want the result in decimal form, we can convert one of the integers into a float using type casting.
Types of Type Casting
There are mainly two types of type casting in C:
- Implicit Type Casting (Automatic Conversion)
- Explicit Type Casting (Manual Conversion)
1. Implicit Type Casting (Automatic Conversion)
In implicit type casting, the conversion is done automatically by the compiler. It usually happens when a smaller data type is converted into a larger data type.
Example:
#include <stdio.h>
int main() {
int num = 10;
float result = num + 2.5;
printf("Result = %f", result);
return 0;
}
Output:
Result = 12.500000
Explanation:
- The integer variable num is automatically converted into float.
- This conversion happens during the calculation.
- This process is called implicit type casting.
- It maintains consistency in calculations between different data types.
2. Explicit Type Casting (Manual Conversion)
In explicit type casting, the conversion is done manually by the programmer using a casting operator. This gives more control over the conversion process.
Syntax:
(data_type) expression
Example:
#include <stdio.h>
int main() {
int a = 5, b = 2;
float result = (float)a / b;
printf("Result = %f", result);
return 0;
}
Output:
Result = 2.500000
Explanation:
- The variable a is manually converted into float.
- Now the division is performed in floating-point form.
- This gives the correct decimal result.
- This manual conversion is called explicit type casting.
Common Type Casting Conversions
| From Type | To Type | Example |
|---|---|---|
| int | float | (float)5 → 5.0 |
| float | int | (int)3.7 → 3 |
| char | int | (int)'A' → 65 |
Why is Type Conversion Important?
- To perform calculations correctly.
- To avoid data loss and unexpected results.
- To make different data types compatible with each other.
- To improve program flexibility.
Data Loss During Type Casting
Sometimes converting a larger data type into a smaller data type may cause data loss.
Example:
#include <stdio.h>
int main() {
float num = 9.8;
int value = (int)num;
printf("Value = %d", value);
return 0;
}
Output:
Value = 9
Explanation:
- The decimal part
.8is removed during conversion. - Only the integer part is stored.
- This is called data loss.
Summary:
- Type casting converts one data type into another.
- Implicit type casting is done automatically by the compiler.
- Explicit type casting is done manually by the programmer.
- Type casting helps perform accurate calculations.
- Improper conversion may cause data loss.