Implicit and Explicit Type Conversions in C Language



Type conversions change an expression from one data type to another. conversions can utilize many features of type hierarchies or data representation.

  • Implicit type conversion
  • Explicit type conversion

Implicit Type Conversion

Implicit type conversions, also known as type casting or type transformation, are automatic type conversions performed by the compiler. Most programming languages have compilers that handle type transformation automatically.

When operands are of different data types, the compiler automatically performs implicit type conversions by converting the smaller data type into a larger one.

int i,x;
float f;
double d;
long int l;

The expression above in the end evaluates to a ?double' value

Example: Printing Lowercase Letters

In the example below, we print lowercase letters from 'a' to 'z' by using ASCII values 97 to 122. The prinf() function converts and displays each value as a character. Following is an example for implicit type conversion ?

#include <stdio.h>
int main() {
   int x;
   for(x = 97; x <= 122; x++) {
       // Implicit casting from int to char %c
       printf("%c", x);
   }
   return 0;
}

Example: Implicit Integer to Float

Let's demonstrate implicit type conversion by assigning an integer value to a float variable. This C program shows this process and prints the float value.

#include <stdio.h>
int main(){
   int i = 40;
   float a;
   // Implicit conversion
   a = i;
   printf("implicit value: %f", a);
   return 0;
}

The result is generated as follows ?

Implicit value:40.000000

Explicit Type Conversion

Explicit type conversion is performed by the user by using (type) operator. Before the conversion is performed, a runtime check is done to see if the destination type can hold the source value.

int a,c;
float b;
c = a +(int)b

Here, the resultant of ?a+b' is converted into ?int' explicitly and then assigned to ?c'.

Example: Printing Lowercase Letters

Here is an example of explicit type conversion. This C program prints lowercase letters 'a' to 'z' by explicitly casting ASCII values 97 to 122 from int to char.

#include <stdio.h>
int main() {
   int x;
   for(x = 97; x <= 122; x++) {
   /* Explicit casting from int to char */
       printf("%c", (char)x); 
   }
   return 0;
}

Let us see the difference between the two types of conversions with examples ?

Example: Converting Integer to Short

Here, we convert an integer I to a short an explicitly, then print the value of a. It specifies type casting and basic output/input operations.

#include <stdio.h>
int main() {
    int i = 40;
    short a;
    // Explicit conversion
    a = (short)i;
    printf("explicit value: %d
", a); return 0; }

The result is obtained as follows ?

Explicit value:40
Updated on: 2024-12-12T17:02:45+05:30

31K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements