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.

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:

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:

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.

Expected Output:

3 thoughts on “Explicit Type Conversion in C

Leave a Comment