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 :
float num1 = 3.5; int num2 = 6; float num3 = 99.7; float result = num1 + num2 + num3;
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.
#include<iostream> #include<conio.h> using namespace std; int main() { float num1 = 3.7 ; int num2 = 4 ; float result = num1 * num2 ; cout << "The result of the expression is : " << result ; getch(); return 0; } /* The result of the expression is : 14.8 */
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.
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 :
#include<iostream> #include<conio.h> using namespace std; int main() { int num1 = 65 ; char ch; ch = (char) num1; cout << "The value of ch is :" << ch ; getch(); return 0; } /* OUTPUT The value of ch is :A */
In this program, we have type cast an integer variable ‘num1’ having the value 90 to a char variable ‘ch’ using the statement
ch = (char) num1;
The syntax for type casting is : (type) expression
Here is a preview of the program.
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.