Type casting
In c, it permits the mixing of constants and variables of different data types in an expression. Typecasting is defined as the conversion of the datatype of one variable to another data type.
There are two ways of typecasting in c –
1. Implicit type casting
2. Explicit type casting
1. Implicit type casting:
C automatically converts any intermediate values to the proper type so that the expression can be evaluated without losing any significance. This automatic conversion is known as implicit type conversion. All the data types of the variables are upgraded to the data type of the variable with the largest data type.
Example:
#include<stdio.h>
int main()
{
int a = 7;
float b = 5.3,c;
c = a+b;
printf(“The value of c is : %f”,c);
return 0;
}
The value of c is : 12.300000
Explanation :
Here the value of C will be 12.3, where the value of ‘a’ will be implicitly converted to float.
2. Explicit type casting :
This process is also called type casting and it is user-defined. Here the user can typecast the result to make it of a particular data type.
Syntax: (datatype)expression
#include<stdio.h>
int main()
{
float x = 11.2;
// Explicit conversion from float to int
int sum = (int)x + 1;
printf(“sum = %d”, sum);
return 0;
}
sum = 12