c-plus-plus
  1. c-plus-plus-type-conversion-in-c

C++ Misc Type Conversion

In C++, there are various ways of converting one data type to another. These conversions can be implicit or explicit.

Syntax

There are different syntaxes for type conversion in C++, depending on the method used. Here are some examples:

Explicit Conversion

C-style casting

To perform a C-style casting, you use the following syntax:

(type) expression

For example:

double d = 3.14159;
int i = (int) d;

Static_cast

To perform a static_cast, you use the following syntax:

static_cast<type>(expression)

For example:

double d = 3.14159;
int i = static_cast<int>(d);

Implicit Conversion

Type Promotion

Type promotion happens when a smaller data type is automatically converted to a larger data type. For example, in an arithmetic operation between an int and a float, the int is promoted to a float.

int i = 10;
float f = 3.14;

float result = i + f; // i is promoted to float

Type Conversion with Assignment

Type conversion also happens automatically when you assign a value of one data type into a variable of another data type.

int i = 10;
float f = i; // i is converted to float

char c = 'A';
int j = c; // c is converted to int

Example

#include <iostream>
using namespace std;

int main() {
    int i = 10;
    float f = 3.14;

    // C-style casting
    float result1 = (float) i + f;

    // static_cast
    int result2 = static_cast<int>(f);

    cout << "Result 1: " << result1 << endl;
    cout << "Result 2: " << result2 << endl;

    // implicit conversion
    float result3 = i + f;
    int j = 'A';

    cout << "Result 3: " << result3 << endl;
    cout << "J: " << j << endl;

    return 0;
}

Output

Result 1: 13.14
Result 2: 3
Result 3: 13.14
J: 65

Explanation

In the above example, we show different ways of doing type conversion in C++. We use both explicit and implicit conversions to show how they work in practice.

Use

Type conversion is used extensively in C++ programs to manipulate data of different types. It is especially important when working with libraries or APIs that use different data types.

Important Points

  • Type conversion can be done implicitly or explicitly in C++.
  • Implicit conversion happens automatically when you assign values of one type into a variable of another type.
  • Explicit conversion can be done using C-style casting or static_cast.
  • Type promotion happens when a smaller data type is automatically converted to a larger data type.
  • Type conversion is used extensively in C++ programs to manipulate data of different types.

Summary

Type conversion in C++ is an important feature that allows you to convert one data type to another. It can be done explicitly or implicitly and is used extensively in programs to manipulate data of different types.

Published on: