TYPE CONVERSION in c++

 TYPE CONVERSION

converting a value from one data type to another. It can be done either implicitly (automatically by the compiler) or explicitly (manually by the programmer). 


1. Implicit Type Conversion (Type Promotion)

This is done automatically by the compiler when converting a smaller data type to a larger data type or when compatible types are involved.

Example:

#include <iostream>

using namespace std;

 

int main() {

    int intVar = 10;

    double doubleVar = intVar; // Implicit conversion (int to double)

   

    cout << "Integer: " << intVar << endl;

    cout << "Double: " << doubleVar << endl;

    return 0;

}

Output:

Integer: 10

Double: 10.0000

 Advantages:

  • Convenience
  • Ease of use

Drawbacks:

  • Precision loss
  • Performance issues
  • Unintended conversions

2. Explicit Type Conversion (Type Casting)

In explicit conversion, the programmer specifies the type to which a value should be converted.

Syntax:

(type) expression;


Example:

#include <iostream>

using namespace std;

 

int main() {

    double doubleVar = 10.5;

    int intVar = (int)doubleVar; // Explicit conversion using C-style casting

   

    cout << "Double: " << doubleVar << endl;

    cout << "Integer: " << intVar << endl;

    return 0;

}

Output:

Double: 10.5

Integer: 10

 

Advantages:

  • Control
  • Versatility

Drawbacks:

  • Complexity
  • Error-prone
  • Potential for misuse

Common Casting Operators in C++:

  1. static_cast.
  2. dynamic_cast
  3. const_cast
  4. reinterpret_cast


Post a Comment

0 Comments