Type Conversion in C++
Introduction to Type Conversion
The method of type conversion in C++ involves utilizing the conversion operator during program design to change one data type to another. Depending on what we want the program to perform, type casting causes the compiler to automatically switch from one data type to another.Syntax:
int a; float b; b = (float) a;
Types of Type Conversion in C++:
- Implicit conversion
- Explicit conversion(also known as typecasting).
Implicit Conversion:
- In C++, implicit type conversion is used to change any variable’s data type without changing the value it stores.
- Without changing any of the values kept in the data variable, it executes the conversions.
Explicit Conversion:
- The user converts types explicitly by using the (type) operator.
- The destination type’s ability to store the source value is checked at runtime prior to the conversion being carried out.
Example 1:
Run
#include<stdio.h> using namespace std; int main() { // Initializing variables int x= 19, y=2; float div; // type conversion div=float(x)/y; cout << "The output : " << div; return 0; }
Output:
The output : 9.5
Advantages of Type Conversion:
- Programmers can change one data type to another by using type conversion.
- The program is made lighter by type conversion.
Example 2:
Run
#include<stdio.h> using namespace std; int main() { // Initializing variables int x = 19, y = 2; char c = 'x'; // Type conversion double div; div = (double)x / y c = c + 2; cout << "The output of Implicit conversion : " << c << endl; cout << "The output of Explicit conversion : " << div ; return 0; }
Output:
The output of Implicit conversion : z The output of Explicit conversion : 9.5
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment