C++ allows us to convert data of one type to that of another. This is known as type conversion.
There are two types of type conversion in C++.
- Implicit Conversion
- Explicit Conversion (also known as Type Casting)
Implicit Type Conversion
The type conversion that is done automatically done by the compiler is known as implicit type conversion. This type of conversion is also known as automatic conversion.
Example
num_int = 9
num_double = 9
Explicit Type Conversion
When the user manually changes data from one type to another, this is known as explicit conversion. This type of conversion is also known as type casting.
There are three major ways in which we can use explicit conversion in C++. They are:
- C-style type casting (also known as cast notation)
- Function notation (also known as old C++ style type casting)
- Type conversion operators
C-style Type Casting
As the name suggests, this type of casting is favored by the C programming language. It is also known as cast notation.
The syntax for this style is:
(data_type)expression;
Example
// initializing int variable
int num_int = 26;
// declaring double variable
double num_double;
// converting from int to double
num_double = (double)num_int;
Function-style Casting
We can also use the function like notation to cast data from one type to another.
The syntax for this style is:
data_type(expression);
Example
// initializing int variable
int num_int = 26;
// declaring double variable
double num_double;
// converting from int to double
num_double = double(num_int);
Type casting
Example
#include <iostream>
using namespace std;
int main() {
// initializing a double variable
double num_double = 9.56;
cout << "num_double = " << num_double << endl;
// C-style conversion from double to int
int num_int1 = (int)num_double;
cout << "num_int1 = " << num_int1 << endl;
// function-style conversion from double to int
int num_int2 = int(num_double);
cout << "num_int2 = " << num_int2 << endl;
return 0;
}
Output
num_double = 3.56
num_int1 = 3
num_int2 = 3
No comments:
Post a Comment