Your browser doesn't support JavaScript Type Conversion - Windows Programming

Type Conversion

Type casting refers to the practice of changing variable types. 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.

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 is the loss of the sign when signed is implicitly converted to unsigned or an overflow can occur when long is implicitly converted to float. 

// An example of implicit conversion 
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 specify 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:

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