Converting one datatype into another is known as type casting or, type-conversion. For example, if you want to store a ‘long’ value into a simple integer then you can type cast ‘long’ to ‘int’. You can convert the values from one type to another explicitly using the cast operator .
As follows :− (type_name) expression
Example :- int x;
float y;
y = (float) x;
Types of Type Casting in C :- Thare are two types of type-casting.
Implicit type conversion in C happens automatically when a value is copied to its compatible data type. During conversion, strict rules for type conversion are applied. If the operands are of two different data types, then an operand having lower data type is automatically converted into a higher data type. This type of type conversion can be seen in the following example.
Example :-
#include <stdio.h>
main()
{
int number = 1;
char character = ‘k’; /*ASCII value is 107 */
int sum;
sum = number + character;
printf(“Value of sum : %d\n”, sum );
}
Output :- The result is 7.000000
We cannot perform implicit type casting on the data types which are not compatible with each other such as:
In implicit type conversion, the data type is converted automatically. There are some scenarios in which we may have to force type conversion. Suppose we have a variable div that stores the division of two operands which are declared as an int data type.
Example :-
#include <stdio.h>
// Driver Code
int main()
{
// Given a & b
int a = 15, b = 2;
float div;
// Division of a and b
div = a / b;
printf(“The result is %f\n”, div);
return 0;
}
Output :- The result is 7.000000
In C programming, there are 5 built-in type casting functions.
Advantages of Type Casting :-