

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Type Conversion in C++
Here we will see what are the type conversion techniques present in C++. There are mainly two types of type conversion. The implicit and explicit.
Implicit type conversion
This is also known as automatic type conversion. This is done by the compiler without any external trigger from the user. This is done when one expression has more than one datatype is present.
All datatypes are upgraded to the datatype of the large variable.
bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double
In the implicit conversion, it may lose some information. The sign can be lost etc.
Example
#include <iostream> using namespace std; int main() { int a = 10; char b = 'a'; a = b + a; float c = a + 1.0; cout << "a : " << a << "\nb : " << b << "\nc : " << c; }
Output
a : 107 b : a c : 108
Explicit type conversion
This is also known as type casting. Here the user can typecast the result to make it to particular datatype. In C++ we can do this in two ways, either using expression in parentheses or using static_cast or dynamic_cast
Example
#include <iostream> using namespace std; int main() { double x = 1.574; int add = (int)x + 1; cout << "Add: " << add; float y = 3.5; int val = static_cast<int>(y); cout << "\nvalue: " << val; }
Output
Add: 2 value: 3
- Related Questions & Answers
- Type Conversion in Python
- What is Type Conversion?
- Data Type Conversion in Python
- Difference Between Type casting and Type Conversion
- What is Type conversion in C#?
- What is type conversion in java?
- Catch block and type conversion in C++
- What is the difference between type conversion and type casting in C#?
- How to implement integer type conversion in JShell in Java 9?
- What is the difference between implicit and explicit type conversion in C#?
- What is the importance of '+' operator in type conversion in JavaScript?
- What is the type conversion operator ( ) in Java and how to use it?
- Conversion Functions in SQL
- Narrowing Conversion in Java
- Conversion constructor in C++?
Advertisements