Typecasting in C

CProgrammingServer Side Programming

Typecasting is a method in C language of converting one data type to another.

There are two types of typecasting.

1.Implicit Type casting − This conversion is done by the compiler. When more than one data type of variables are used in an expression, the compiler converts data types to avoid loss of data.

Here is an example of implicit type casting in C language,

Example

 Live Demo

#include <stdio.h>
int main() {
   int a = 10;
   char b = 'S';
   float c = 2.88;
   a = a+b;
   printf("Implicit conversion from character to integer : %d\n",a);
   c = c+a;
   printf("Implicit conversion from integer to float : %f\n",c);
   return 0;
}

Output

Implicit conversion from character to integer : 93
Implicit conversion from integer to float : 95.879997

2.Explicit Type casting − This conversion is done by user. This is also known as typecasting. Data type is converted into another data type forcefully by the user.

Here is the syntax of explicit type casting in C language,

(type) expression

Here is an example of explicit type casting in C language,

Example

 Live Demo

#include <stdio.h>
int main() {
   float c = 5.55;
   int s = (int)c+1;
   printf("Explicit Conversion : %d\n",s);
   return 0;
}

Output

Explicit Conversion : 6
raja
Updated on 24-Jun-2020 10:48:40

Advertisements