In this tutorial, we will learn about the C++ type conversion with the help of many examples.
C++ allows us to convert data of one type to that of another type. This is
known as type conversion.
There are two types of type conversion.
- Implicit Conversion
- Explicit Conversion
Implicit Type Conversion
The Implicit conversion that is automatically done by the compiler is known as implicit type conversion. This type of conversion is also known as automatic conversion.
Two examples of implicit type conversion.
Example 1: Conversion From int to float
#include "iostream"
using namespace std;
void main()
{
// declaring an int type variable
int num1;
// initializing the variable 'num1' with the value 7
num1 = 7;
// declaring a float type variable
float num2;
// implicit conversion
// assigning int value to a float variable
num2 = num1;
cout << "value of num1 = " << num1 << endl;
cout << "value of num2 = " << num2 << endl;
}
using namespace std;
void main()
{
// declaring an int type variable
int num1;
// initializing the variable 'num1' with the value 7
num1 = 7;
// declaring a float type variable
float num2;
// implicit conversion
// assigning int value to a float variable
num2 = num1;
cout << "value of num1 = " << num1 << endl;
cout << "value of num2 = " << num2 << endl;
}
Output
num1 = 7
num2 = 7
num2 = 7
In this program, we have assigned an int data to a float variable.
0 Comments
if you have any doubt in programming concept please let me know