In C programming, type conversion refers to changing a variable from one data type to another. It can happen automatically (implicit) or manually (explicit or type casting).
Let’s explore this in a simple, step-by-step guide.
What is Type Conversion in C?
Implicit Type Conversion (Type Promotion)
Also called automatic conversion. The compiler automatically converts the smaller data type to a larger one.
Example:
#include <stdio.h>
int main() {
int x = 5;
float y = 2.5;
float result = x + y; // int is promoted to float
printf("Result = %.2f\n", result); // Output: 7.50
return 0;
}
Type Hierarchy (Lower → Higher):
char → int → float → double
Explicit Type Conversion (Type Casting)
Manually convert one data type to another using a cast operator.
Syntax:
(type) expression;
Example:
#include <stdio.h>
int main() {
float num = 5.75;
int converted = (int) num; // Manual type casting
printf("Converted = %d\n", converted); // Output: 5
return 0;
}
Note: Decimal part is truncated, not rounded.
More Examples of Type Conversion
Example 1: Implicit Type Conversion in Expression
int a = 10;
char b = 'A'; // ASCII 65
int result = a + b; // b is promoted to int
Example 2: Explicit Conversion in Division
int a = 5, b = 2;
float result = (float)a / b; // Prevents integer division
Table: Implicit Conversion Example
Operand 1
Operand 2
Result Type
int
float
float
char
int
int
float
double
double
Best Practices
Use type casting to avoid precision loss
Use float or double when working with decimals
Be careful when converting float to int — decimals will be dropped