C - SPLessons
boy2 Chapter 10

Type Casting in C

C - SPLessons

Type Casting in C

shape Description

Type Casting in C which conversion of a variable from one type to another type. When type casting is applied on the variable, latest data type is considered by the compiler as the data type of that variable.

shape Example

int x;
x=(float)8/3;

In the above example, first the variable x is in integer type and then converted to float type and the result will be in float i.e 2.666.

There are mainly two types of Type Casting in C. They are:

Implicit type conversion

shape Description

The automatic conversion of type performed by the compiler can be called as implicit conversion or type promotion. The compiler converts all operands into the data type of the largest operand.

The variable to be converted will be always on the left side of arithmetic operator. The data type of highest operand is given to all the operands. There is no loss of data by using implicit conversion.

Implicit conversion focuses mainly on conversion from “low data type to high data type“.

shape Conceptual
figure

shape Example

int a;
float b,c;
c=a+b; // int is converted to float

Explicit type conversion

shape Description

Explicit type of conversion is done by the programmer by posing the data type of the expression of specific type. The conversion focuses mainly on conversion from “high data type to low data type“. There will be loss of data by using explicit conversion.

Explicit Type casting in C is done in the following way.

(data_type)expression;

where, data_type is any valid c data type, and expression may be constant, an expression or a variable.

To avoid the loss of information while performing the explicit conversions following rules have to be followed.


shape Example - 1

float a=1.23;
int b=(int)a;

In the above example, float value is 1.23. When float is converted to integer data type, only ‘1’ will be the output. The remaining ‘0.23’ is lost due to explicit conversion.

shape Example - 2

#include<stdio.h>
#include<conio.h>
void main()
{
	      int i=20;
	      short p;

	      p = (short) i; // Explicit conversion
	      printf("Explicit value is %d",p);
	
	      getch();
}

Output:

Explicit value is 20

Summary

shape Key Points

  • Type Casting in C helps in conversion of variable type.
  • Implicit conversion is performed from low data type to high data type and Explicit conversion functions in reverse to implicit.

shape Programming
Tips

When a result is assigned to variable of different type, there may be a loss of data during conversion. Be careful about it.