
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Type Conversion in Python
- Data Type Conversion in Python
- What is Type Conversion?
- 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?
- Narrowing Conversion in Java
- Conversion constructor in C++?
- Conversion Operators in C++

Advertisements