Type Conversions in C++

Type casting refers to converting one data type to another. There are 2 types of type casting.They are a)implicit type casting and b)explicit type casting.

a)Implicit conversion or casting is an automatic conversion.For example:

  • int i = 1;

    long l;

    l = i;

  • Here, C++ automatically converts the data type for us from int to long.Also , if you assign a zero value to a bool variable, it will be converted to false. Any non-zero value is converted to true.

b)Explicit conversion or casting is a forceful conversion.For example:

  • When you want to explicitly perform a conversion or cast, you can use the type cast features of C++.

    • long l = (long)i;

  • C++ also provides a cast operator that is more restrictive in its usage. This in the form static_cast (type)This static cast operator can be used for converting numeric values or to numeric values. As an example:

    char ch;

    int i = 65;

    float f = 2.5;

    double dbl;

    ch = static_cast<char>(i); // int to char

    dbl = static_cast<double>(f); // float to double

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: