Explicit Type Conversion in C

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.

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:

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:

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:

Expected Output:

4 thoughts on “Explicit Type Conversion in C

  1. this website is great for learning C, not like tutorialspoint.com ,which i think is too technical for beginners.

Leave a Comment

%d bloggers like this: