
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements