Type Conversion

Type casting refers to the practice of changing a variable of one data type into another. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to a float. Casting allows you to make this type of conversion explicit, or to force it when it wouldn’t normally happen.

Type conversion in C can be classified into Implicit and explicit type conversions.

Implicit Type Conversion

Implicit or automatic type conversions are performed automatically by the C compiler without any action on the part of the programmer. Data types of the variables are upgraded to the data type of the variable with the largest data type. Implicit conversions can result in loss of information. An example the loss of the sign when signed is implicitly converted to unsigned or an overflow can occur when long is implicitly converted to float.

int main()
{
int x = -5; // integer x
float z = x; // x is implicitly converted to float;
char c=x+40;// x is implicitly converted to the char character #;
unsigned int y=x;// x is implicitly converted to unsigned int with loss of data;
printf("z = %f", z);
printf("\n");
printf("c = %c", c);
printf("\n");
printf("y = %u", y);
return 0;
}


Explicit Type Conversion

Explicit type casting is user-defined and uses the cast operator to explicitly control type conversions. A variable typecast consists of a type name, in parentheses, before an expression. These casts can be performed on arithmetic expressions and pointers. The resulting expression is converted to the type specified by the cast. One use of an explicit cast is to avoid losing the fractional part of the answer in an integer division. The syntax is:

(type) expression

int main()
{
float a;
int b = 2, c = 3;
a = (float) b / (float) c; //type-casting
printf("%f", a);
}