OverIQ.com

Explicit Type Conversion in C

Last updated on July 27, 2020


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

1
2
3
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.

The Cast operator #

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

where datatype refers to the type you want the expression to convert to. 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.

Note that in the above statement the cast operator only applies to the variable a, not to b or a/b.

Another important point to note 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 be thinking that this statement is the 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 cast operator in action:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include<stdio.h>

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:

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