What is Type Casting in C?

What is Type Casting in C?
Type casting is the process in which the compiler automatically converts one data type in a program to another one. Type conversion is another name for type casting. For instance, if a programmer wants to store a long variable value into some simple integer in a program, then they can type cast this long into the int. Thus, the method of type casting lets users convert the values present in any data type into another data type with the help of the cast operator, like:
(type_name) expression
Let us take a look at the following example to understand how we can utilise the cast operator for dividing an integer variable with another one by performing it as an operation of floating-point type:
#include <stdio.h>

main() {

int total = 17, values = 5;

double average;

average = (double) total / values;

printf(“The average of all the values available with us is : %f\n”, average );

}
The compilation and execution of the code mentioned here would generate the following output of the program:

The average of all the values available with us is :
3.400000
You must note here that the precedence of the cast operator is much higher than that of the division operator. Thus, the program would first convert the value of total into the double type. After this, it will finally divide this value with the help of count yielding of the double value.

As a matter of fact, the process of type conversion or type casting can be very implicit. It means that the compiler is capable of performing it automatically. Conversely, we can specify the data type explicitly using the cast operator. Both the methods are okay, but using the cast operator whenever in need is considered a better programming practice (explicit).

Syntax for Type Casting in C
int val_1;

float val_2;

// Body of program

val_2 = (float) val_1; // type casting of the values


Posted on by