Type Conversion in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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

 Live Demo

#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
raja
Published on 03-Jan-2020 15:40:10
Advertisements