Type conversion/Type casting
When constants and variables of different types are mixed in an expression, they are converted to the same type.
The process of converting one predefined type into another defined type is called type conversion.
C language facilitates the type conversion in two forms:
(i). implicit type conversion
(ii).Explicit type conversion
(i). implicit type conversion:
An implicit type conversion (or automatic type conversion) is a conversion performed by the compiler without programmers intervention. An implicit conversion is applied generally whenever different data types are intermixed in an expression (called mixed mode expression), so as not to lose information.
The C compiler converts all operands upto the type of the largest operand, which is called type promotion. This is done/performed operation by operation.
Once these conversion rules have been applied , each pair of operands is of the same type and the result of each operation is the same as the type of both the operands.
(ii).Explicit type conversion:
An explicit conversion is user defined , that forces an expression to be of specific type.
Type casting in C is done as shown below:
Syntax:
(type) expression
Where type is a valid C data type to which the conversion is to be done. “type” is known as cast operator.
/* type conversion */ #include<stdio.h> int main() { int a=10,b=4,c; float c1; //implicit conversion c=a/b; printf("c = %d\n",c); c1=a/b; printf("c1 = %f\n",c1); //explicit conversion c1=(float)a/b; printf("c1 = %f\n",c1); return(0); }
/* Output */ c = 2 c1 = 2.000000 c1 = 2.500000