This lesson focuses on expressions consisting of mixed data types. The C++ compiler has a way to deal with expressions that contains variables or constants which have different data types. So if we have two different types of variables/constants in an expression, they can be converted to one single type (either by the compiler or explicitly by the programmer). This process is known as type conversion in C++.

For example, consider the following code snippet :

In the above code, the last statement is an expression that adds up two float variables (num1 and num3) and one integer variable(num2) and stores the result in a float variable(result).

Such mixed expressions, as stated earlier, can be dealt with in two ways in C++. Let’s see what these methods are using some programming examples!

1. Implicit Type Conversion

Implicit Type Conversion is performed by the compiler on its own when it encounters a mixed expression in the program.

This is also known as automatic conversion as it is done automatically by the compiler without the programmer’s assistance.

In this type of conversion, all operands are converted upto the type of the largest operand in the expression. This is also called as type promotion. Thus, the result of the expression is also of the type of the largest operand.

Let us have a look at the following program to understand this in detail.

In this program, as you can see, we are multiplying an integer (num2) with a float (num1). So the compiler converts ‘ num2 ‘ to a float and then it is multiplied with num1. The product is then stored in ‘result’ .

Here is the preview of this program.

 Implicit Type Conversion in C++

2. Explicit type conversion

When the programmer explicitly changes the data type of an operand or an expression, then this is called as explicit type conversion.

It is also known as type casting.

To understand this, consider the following code snippet :

In this program, we have type cast an integer variable ‘num1’ having the value 90 to a char variable ‘ch’ using the statement

The syntax for type casting is : (type) expression 

Here is a preview of the program.

Explicit Type Conversion in C++

The example we have used here is quite simple, we can understand the power and importance of type casting when we deal with complex expressions in C++.

Hope you’re clear with the topic. Let us know your queries. Drop your comments below.


Founder & Senior Editor of and Editor at Sakshi is currently pursuing MCA. She is a foodie and has a unique love for learning computer programming languages. Follow her on Google + | Facebook | Twitter. Contact her at [email protected] for feedback and sending tips.

Tags: , , , ,

Leave A Response