Introduction
When the data is converted from one to another data type, then it's known as typecasting. Typecasting is nothing but converting the kind of data. Using typecasting, the type of the data may be modified but now not the data itself. It is one of the essential ideas introduced in 'C' programming.
You can also read about the jump statement, C Static Function
Types of Typecasting operations
C programming provides two types of type casting operations:
1. Implicit type casting
Implicit type casting means conversion of data types without losing their original means. Typecasting is essential when you need to change data types without converting the values stored inside the variable.
Implicit type conversion in C occurs automatically when a value is copied to its like-minded data type. in the course of the conversion, strict rules for type conversion are applied. If the operands are of two different data types, then an operand with a lower one is automatically converted right into a higher one. This type of type conversion may be seen in the following example.
#include<stdio.h>
int main()
{
short x=10; //initializing variable of short data type
int y; //declaring int variable
y=x; //implicit type casting
printf("%d\n",x);
printf("%d\n",y);
}Output:
10
10Essential Points about Implicit Conversions
- The implicit type of type conversion is also known as standard type conversion. We do no longer require any keyword or unique statements in implicit typecasting.
- Converting from smaller data types into large ones is likewise called type promotion. In the above example, we also can say that the value of s is promoted to type integer.
- The implicit type conversion constantly occurs with the compatible data types.
Also see, Floyd's Triangle in C
2. Explicit type casting
In an implicit type conversion, the data type is converted automatically. There are some scenarios wherein we may additionally need to force type conversion. Suppose we've got a variable div that stores the division of operands declared as an int data type.
int result, var1=10, var2=3;
result=var1/var2;In this case, after the division is completed on variables var1 and var2, the result stored in the variable "result" may be in an integer format. The value stored in the variable "result" loses its meaning on every occasion. It does not don't forget the fraction part, which is usually obtained within the division of numbers.
To force the type conversion in such conditions, we use explicit typecasting.
It requires a type casting operator. The overall syntax for type casting operations is as follows:
(type-name) expressionExample
#include<stdio.h>
int main()
{
float x = 1.2;
//int y = x; //Compiler will throw an error for this
int y = (int)x + 1;
printf("Value of x is %f\n", x);
printf("Value of y is %d\n",y);
return 0;
}Output:
The value of x is 1.200000
The value of y is 2
You can also read about C dynamic array, Tribonacci Series and Short int in C Programming




