Sometimes we have a value of one data type but need to use it as another data type.
For example, we may have an int but want to use it as a float.
C provides two ways to handle this:
Type Conversion
Type Casting
Type Conversion
Type conversion is the process of converting one data type into another automatically by the compiler.
For example:
int a = 10;
float b = a;Here, a is an int, but it is automatically converted to float.
int 10
↓
float 10.0This is called implicit type conversion.
Example
int a = 10;
float b = 3.5;
float result = a + b;C automatically converts a from int to float before performing the addition.
Type Casting
Type casting is the process of manually converting a value from one data type to another using the programmer's instruction.
We use the following syntax:
(data_type) valueFor example:
int a = 10;
float result = (float)a;Here, (float) tells the compiler to treat a as a float.
Example with Division
Consider:
int a = 5;
int b = 2;
float result = a / b;You might expect 2.5, but the result is 2.0 because both operands are integers, so integer division happens first.
To get 2.5, we can use type casting:
float result = (float)a / b;Now a is converted to float, so floating-point division is performed.
5 / 2
↓
2.5Type Conversion vs Type Casting
Type Conversion | Type Casting |
|---|---|
Usually automatic | Explicitly performed by programmer |
Also called implicit conversion | Also called explicit conversion |
Compiler performs the conversion | Programmer specifies the target type |
Example: | Example: |
Simple Example
#include <stdio.h>
int main()
{
int a = 5;
int b = 2;
printf("%d\n", a / b);
printf("%f\n", (float)a / b);
return 0;
}Output:
2
2.500000The first calculation uses integer division, while the second uses type casting to perform floating-point division.
One Important Point
When converting from a type with a larger range or precision to a smaller one, data may be lost.
For example:
float price = 99.99;
int value = (int)price;Now value becomes:
99The decimal part is discarded.
In Simple Words
Type conversion happens automatically, while type casting is done explicitly by the programmer.
A simple way to remember:
Conversion → Compiler does it
Casting → Programmer does it