Explicit Type Conversion in C

Type conversions discussed in the previous lesson are done by the compiler automatically. In certain situations, we want to have more control over how conversion takes place. Let's take an example.

float f;
int a = 20, b = 3;
f = a/b

The value of f  will be 6.000000 instead of 6.666666 because operation between two integers yields an integer value. Sure one way to solve this problem is to use mixed mode arithmetic and  change the type of either a or b to double or float. Changing the type of variables is not always feasible and is certainly not a good program design.

Enter the Explicit type casting in C.

A cast operator is a unary operator used to temporarily convert constant, variable or expression to a particular type. The syntax of cast operator is:

Syntax: (datatype)expression

The data type desired, such as int, float are substituted for the word datatype.

So if we write the above statement as:

f = (float)a/b;

Then we will get the correct answer i.e 6.666666.

Here is how the cast operator works.

First, it converts the variable a which of type int to type float temporarily. We already know that the operation between a float and int operand yields a float result, that's why answer comes out to be 6.666666 instead of 6.000000.

The important thing to note in the previous statement is that data type of variable a is float till the execution of the statement only. After that, it will be treated as int.

Before we leave this topic, consider the following statement:

f = (float)(a/b);

You might think this statement is same as the previous one ( i.e f = (float)a/b;  ), but it is not, here is why.

Here first the expression a/b is evaluated then it results is converted to float because of typecasting and eventually assigned to f.

The following program demonstrates typecasting.


int main()
    int a = 25, b = 13;
    float result;

    result = a/b;

    // display only 2 digits after decimal point
    printf("(Without typecasting) 25/13 = %.2f\n", result );  

    result = (float)a/b;

    // display only 2 digits after decimal point
    printf("(With typecasting) 25/13 = %.2f\n", result ); 

    // signal to operating system everything works fine
    return 0;

Expected Output:

(Without typecasting) 25/13 = 1.00
(With typecasting) 25/13 = 1.92