C - SPLessons

Chapter 10

Type Casting in C

Type Casting in C

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.

int x;

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

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“.

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

Explicit type conversion

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.


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.

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.

void main()
	      int i=20;
	      short p;

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


Explicit value is 20


  • 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.

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