On this page, we will learn about type casting, how to use it, types of type casting, implicit type casting, explicit type casting, widening type casting, narrowing type casting, sign conversion type casting, and an example of type casting in C.
Type casting in C refers to the conversion of one data type to another. This is sometimes necessary when performing arithmetic or other operations, as C requires that operands have the same data type.
Type casting can be implicit or explicit. Implicit type casting occurs when the compiler automatically converts one data type to another. For example, if you add an integer and a float, the integer will be implicitly converted to a float before the addition is performed. Explicit type casting, on the other hand, is when the programmer manually converts one data type to another using the cast operator.
The cast operator is denoted by enclosing the desired data type in parentheses and placing it before the operand to be converted. For example, if you want to convert an integer variable x to a float, you can use the following syntax:
float y = (float) x;
This tells the compiler to treat the integer value stored in x as a float, and then assign it to the variable y.
It is important to note that type casting can result in a loss of precision or even data loss, depending on the data types being converted. Therefore, it should be used with caution and only when necessary.
In C, there are different types of type casting, each with their own specific purpose. In this article, we will explore the different types of type casting in C.
int a = 5;
float b = 3.2;
float sum = a + b; // Implicit type casting: a is promoted to float
In the above code, the value of a is automatically converted from an int to a float to match the data type of b.
(type_name) expression
float a = 3.2;
int b = (int) a; // Explicit type casting: a is cast to int
In the above code, the value of a is explicitly cast to an int using the (int) type cast operator.
long a = 123456789;
int b = (int) a; // Narrowing type casting: a is cast to int, potential data loss
unsigned int a = 4294967295; // Max value for unsigned int
int b = (int) a; // Sign conversion type casting: a is cast to int, potential data loss due to overflow
In the above code, the value of a is explicitly cast to an int, which can result in overflow and potential data loss.
#include<stdio.h>
int main(){
int a = 3;
int b = 4;
int total = a + b;
float median1 = total / 2;
printf("%f \n", median1);//'\n' is used to go to new line.
float median2 = (float)total / 2; //type casting.
printf("%f \n", median2);
printf("%.2f \n", median2); // .2f used for printing upto two decimal point.
return 0;
}
3.000000
3.500000
3.50
Overall, type casting is a useful tool in C programming that allows for greater flexibility and precision when working with different data types.