Typecasting in C allows you to explicitly convert a value from one data type to another. When you assign a variable of one data type to a variable of another data type, the compiler may perform an implicit conversion if it’s safe (e.g., from a smaller data type to a larger one), or you can explicitly cast the variable.
let’s demonstrate type casting with examples using int, char, and float data types:
Type Casting from char to int:
#include <stdio.h>
int main()
{
char c = 'B';
int a = (int)z; // Typecasting char to int
printf("Integer: %d\n", a); // Output: Integer: 66
}
So what’s happening in the background?
Character type is 1 byte and integer type is 4 bytes when you are trying to assign 1 byte data to a 4 byte variable, the least significant byte is filled with the assigned 1 byte value, rest of the bytes are left with zeros.
Typecasting from int to char:
Well type casting from a bigger size to a smaller size is not preferable here is why
#include <stdio.h>
int main()
{
int a = 560;
char c = (int)a;
printf("The value of c is %c\n"); // undefined behaviour
}
so what is that undefined behaviour?
the above diagram shows that only least significant byte of data is copied i.e., 00110000. its equivalent value is 48 which is ASCII value of character ‘0’. so if you try to print the value of c it prints 0. as the value assigned has a valid ASCII value it is printing a character. if the value stored has no valid ASCII value it print a garbage character.
Typecasting from char to float:
#include <stdio.h>
int main() {
char c = 'A';
float f = (float)c; // Typecasting char to float
printf("Float: %f\n", f); // Output: Float: 65.000000
return 0;
}
Prev << Operators in C
Next >> Conditional statements in C