Typecasting or type conversion is converting an operand of one type to another type.

Typecasting in C is performed in two different ways

  • Implicit type conversion
  • Explicit type conversion

Implicit type conversion

The C compiler automatically performs type conversion when an operation is performed on operands of two different types.

There are two scenarios for implicit type conversion.

  • Lower type to higher type
  • Higher type to lower type

Lower type to Higher type

In this case, the lower data type will be converted to a higher data type.

An example of this is performing an arithmetic operation (i.e. +, -, x,  /) between two different operands.

Data loss won’t happen in this scenario because the resultant type is large enough to store the source type. See the below example for a better understanding of this.

#include <stdio.h>
int main(){
  float a = 10.543;
  int b = 20;
  float c = a + b;
  printf("%f", c);
  return 0;
}

In the above example, implicit type casting is being performed between float and int types. So here the int type (i.e. lower type) will be automatically converted into float type (i.e. higher type) and the resultant type will be float.

Higher type to Lower type

An example of this is performing an assignment operation (i.e. =, >=, <=, etc.) between two different operands.

Data loss may happen in this case because the resultant type is small enough to store the source type. See the below example for a better understanding of this.

#include <stdio.h>
int main(){
  float a = 20.456;
  int b = a;  // b is lvalue & a is Rvalue
  printf("%d", b); // 20.456(float) will be converted to 20(int).
  return 0;
}

In the above example, the larger value type will automatically be converted to smaller when we assign a larger type to a smaller type. So, the 20.456 is truncated to 20.

Explicit type conversion

C compiler follows a certain set of rules to perform the implicit type conversion. Overriding all those rules is nothing but explicit type conversion.

In general, explicit type conversion in C is forcing the C Compiler to convert an object of one type to the other type. This can be done by prefixing the type to the expression.

syntax: (type-name) expression
eg: int c = (int)1.4 + 3

During explicit type conversion, data loss may or may not happen and it is completely dependent on the source and resultant types.

#include <stdio.h>
int main()
{  
  int a = 10;
  float b = 20.7;
  int c = a + (int) b;
  // Explicit type casting...
  printf("%d", c);
}

In the above example, we are explicitly specifying the C compiler to convert b of type float to int. If we won’t specify explicitly, the C compiler will convert a to float as per the implicit rules

I hope, now you are well aware of type conversion in C. Thanks for reading this article & Happy learning!!

Categorized in:

Tagged in: