In C++ programming, type conversion plays a crucial role in handling different data types efficiently. It refers to the process of converting one data type into another, either automatically or manually.
Type conversions in C++
In C++, type conversion refers to changing a value from one data type to another data type. It can be done either automatically which is known as implicit conversion or manually which is known as explicit casting.
#include <iostream>
using namespace std;
int main() {
int a = 10;
double b = 3.5;
// Implicit conversion (automatic)
double result1 = a + b;
cout << "Implicit conversion result: " << result1 << endl;
// Explicit conversion (manual)
int result2 = a + (int)b;
cout << "Explicit conversion result: " << result2 << endl;
int result3 = a + static_cast<int>(b);
cout << "Static_cast result: " << result3 << endl;
return 0;
}Implicit Conversion
The implicit conversion is also known as promotion or automatic conversion. It is done using a compiler when mixing different data types in an expression. This is done using a smaller data type to a larger one.
Example,
int x = 10;
double y = x; // int automatically converted to doubleExplicit Conversion
The explicit conversion is performed manually with the help of specific syntax by the programmer. The explicit conversion ensures precise control over how data is converted.
Example,
double pi = 3.14159
int n = (int)pi; // result: 3Disclaimer: We have provide you with the accurate handout of “Type conversions in C++“. If you feel that there is any error or mistake, please contact me at anuraganand2017@gmail.com. The above study material present on our websites is for education purpose, not our copyrights.
Images and content shown above are the property of individual organisations and are used here for reference purposes only. To make it easy to understand, some of the content and images are generated by AI and cross-checked by the teachers.