Type Conversion

 C++ allows us to convert data of one type to that of another. This is known as type conversion.

There are two types of type conversion in C++.

  1. Implicit Conversion
  2. Explicit Conversion (also known as Type Casting)

Implicit Type Conversion

The type conversion that is done automatically done by the compiler is known as implicit type conversion. This type of conversion is also known as automatic conversion.

Example

#include <iostream>

using namespace std;

 

int main() {

   int num_int = 9;

   double num_double;

 

   // implicit conversion

   // assigning int value to a double variable

   num_double = num_int;

 

   cout << "num_int = " << num_int << endl;

   cout << "num_double = " << num_double << endl;

 

   return 0;

}

Output

num_int = 9
num_double = 9
 

Explicit Type Conversion

When the user manually changes data from one type to another, this is known as explicit conversion. This type of conversion is also known as type casting.

There are three major ways in which we can use explicit conversion in C++. They are:

  1. C-style type casting (also known as cast notation)
  2. Function notation (also known as old C++ style type casting)
  3. Type conversion operators

 

C-style Type Casting

As the name suggests, this type of casting is favored by the C programming language. It is also known as cast notation.

The syntax for this style is:

(data_type)expression;

Example

// initializing int variable

int num_int = 26;

// declaring double variable

double num_double;

// converting from int to double

num_double = (double)num_int;

 

 

Function-style Casting

We can also use the function like notation to cast data from one type to another.

The syntax for this style is:

data_type(expression);

Example

// initializing int variable

int num_int = 26;

// declaring double variable

double num_double;

// converting from int to double

num_double = double(num_int);

 
Type casting
 Example 
#include <iostream>
using namespace std;
 
int main() {
    // initializing a double variable
    double num_double = 9.56;
    cout << "num_double = " << num_double << endl;
 
    // C-style conversion from double to int
    int num_int1 = (int)num_double;
    cout << "num_int1   = " << num_int1 << endl;
 
    // function-style conversion from double to int
    int num_int2 = int(num_double);
    cout << "num_int2   = " << num_int2 << endl;
 
    return 0;
}
 
Output
 
num_double = 3.56
num_int1   = 3
num_int2   = 3
 
 

 

 

No comments:

Post a Comment