In C programming, managing data types effectively is key to writing efficient, accurate code. One of the fundamental ways to handle data conversion is through typecasting—the process where a programmer explicitly or implicitly converts one data type to another using a casting operator. Typecasting in C allows us to forcefully change data types, making it useful for optimizing code, but it comes with potential risks.
For example, when converting a floating-point number to an integer, as in float pi = 3.14; int integer_pi = pi;
, part of the value is lost, reducing pi
to just 3
. This “narrowing conversion” can lead to data loss and precision issues, and similar issues arise when converting a large integer into a smaller type, like char
or int
.
Typecasting in C is the process where the programmer explicitly converts one data type to another using a casting operator. When typecasting, the target data type can be smaller than the source data type, which is why this kind of conversion is also known as a narrowing conversion.
Example:
Converting float into int
float pi = 3.14;
int integer_pi = pi; // integer_pi becomes 3, losing .14
Converting from int to char:
int x=5;
char ch=x;
Converting long to int:
long largeValue = 2147483648; // Just above the int max limit
int intValue = largeValue; // intValue may wrap around depending on the system
Narrowing conversions can cause:
Implicit type casting: (‘a’ is implicitly promoted to ‘int’)
short a = 5;
int b = 10;
int result = a + b;
Float to Double Promotion:
When a function expects a double and a float is passed as an argument, the float is implicitly promoted to a double.
#include<stdio.h>
void function(double d)
{
printf(“%lf”,d);
}
int main()
{
float f=9.22f;
function(f)
}
Converting int to float:
int x=5;
float y=4.4;
float=x+y;
Converting char to int:
char c=’a’
int ph=c+1
Explicit Typecasting:
Explicit typecasting is a converting from one datatype to another datatype explicity.
Without explicit conversion
—————————–
#include <stdio.h>
// Driver Code
int main()
{
int a=10;
int b=3;
double d;
d=a/b;
printf(“%lf”,d);
return 0;
}
Output :3.00000
With explictit conversion:
//
// typecasting
#include <stdio.h>
// Driver Code
int main()
{
int a=10;
int b=3;
double d;
d=(double)a/b;
printf(“%lf”,d);
return 0;
}
The output is:3.5
Indian Institute of Embedded Systems – IIES