Typecasting in C language
In programming, typecasting, commonly referred to as type conversion, is the process of changing a value from one data type to another. A programmer can switch the data type of a variable or constant in C from one type to another by using a technique called typecasting.
Types of typecasting in C:
- Implicit
- Explicit
a) Implicit typecasting is done automatically by the compiler when a value of one data type is assigned to a variable of another data type. Explicit typecasting is done manually by the programmer using a typecasting operator.
Example:
int num1 = 10;
float num2 = 5.5;
// Implicit typecasting
float result = num1 + num2;
printf("Result = %f\n", result);
In this example, num1 is an integer and num2 is a float. When they are added together, the result is automatically promoted to a float through implicit typecasting.
b) Explicit type casting is done by putting the required data type in front of the value that has to be transformed and writing it inside parentheses. This instructs the C compiler to change the value’s data type to the desired one.
Explicit type casting is done by putting the required data type in front of the value that has to be transformed and writing it inside parentheses. This instructs the C compiler to change the value’s data type to the desired one.
Example:
int a = 5;
float b = (float) a;
In this example, we have declared an integer variable a, and initialized it with the value 5. We then perform an explicit type cast of a to a floating-point data type using (float). The resulting value is stored in a floating-point variable b.
When someone wishes to compute the average temperature of a room in Celsius and wants to present the result in Fahrenheit, that is an actual-world example of explicit type casting in C. To do this, it would be necessary to explicitly typecast the Celsius temperature value to a floating-point data type, after which the Fahrenheit temperature value could be determined using the formula (9/5) * Celsius + 32.
Programmers can transform values of one data type to another using the effective tool known as explicit type casting. To prevent potential data loss or unanticipated outcomes, it should, however, be utilized carefully and with caution.
In conclusion, typecasting is an important concept in C programming that allows us to convert one data type to another. It can be explicit or implicit and should be used with caution to avoid loss of data or precision.