CPP Tutorial



C++ TYPE CONVERSION


🔸 Type Conversion in C++

Type conversion is the process of converting a variable from one data type to another. In C++, there are two main types of type conversion:

  • Implicit Conversion (Type Coercion): Done automatically by the compiler.
  • Explicit Conversion (Type Casting): Done manually by the programmer.

1. Implicit Conversion (Type Coercion)

The compiler automatically converts one data type to another when needed. For example:

int a = 5;
double b = 6.7;
double result = a + b;  // 'a' is implicitly converted to double
  

Here, the integer a is automatically converted to a double before addition.

2. Explicit Conversion (Type Casting)

You can manually convert a variable from one type to another using casting. There are four types of casts in C++:

  • static_cast<type>(expression)
  • dynamic_cast<type>(expression) (used with polymorphism)
  • const_cast<type>(expression) (to add/remove constness)
  • reinterpret_cast<type>(expression) (low-level cast)

For basic type conversion, static_cast is commonly used.

Example of static_cast:

double x = 9.99;
int y = static_cast<int>(x);  // y becomes 9 (fraction discarded)
  

C-style Casting

The old C-style casting looks like this:

int y = (int)9.99;  // y becomes 9
  

But static_cast is preferred in modern C++ because it is safer and clearer.

Example Program: Type Conversion

#include <iostream>

using namespace std;

int main() {
  int a = 10;
  double b = 3.14;

  // Implicit conversion
  double sum = a + b;
  cout << "Sum (implicit conversion): " << sum << endl;

  // Explicit conversion (casting)
  int c = static_cast<int>(b);
  cout << "Value of b after casting to int: " << c << endl;

  return 0;
}
  

Summary

  • Type conversion changes one data type to another.
  • Implicit conversion is automatic.
  • Explicit conversion (casting) is manual and safer using static_cast.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review