Home | | Computer Science 11th std | C++: Type Conversion

Chapter: 11th Computer Science : Chapter 9 : Introduction to C++

C++: Type Conversion

The process of converting one fundamental type into another is called as “Type Conversion”.

Type Conversion

 

The process of converting one fundamental type into another is called as “Type Conversion”. C++ provides two types of conversions.

(1) Implicit type conversion

(2) Explicit type conversion.

 

(1) Implicit type conversion:

 

An Implicit type conversion is a conversion performed by the compiler automatically.

So, implicit conversion is also called as “Automatic conversion”.

This type of conversion is applied usually whenever different data types are intermixed in an expression. If the type of the operands differ, the compiler converts one of them to match with the other, using the rule that the “smaller” type is converted to the “wider” type, which is called as “Type Promotion”.

 

For example:

#include <iostream>

using namespace std;

int main()

{

      int a=6;

      float b=3.14;

      cout << a+b;

}

In the above program, operand a is an int type and b is a float type. During the execution of the program, int is converted into a float, because a float is wider than int. Hence, the output of the above program will be: 9.14

The following Table 9.11 shows you the conversion pattern.



(2) Explicit type conversion

 

C++ allows explicit conversion of variables or expressions from one data type to another specific data type by the programmer. It is called as “type casting”.

 

Syntax:

(type-name) expression;

Where type-name is a valid C++ data type to which the conversion is to be performed.

 

Example:

#include <iostream>

using namespace std;

int main( )

{

      float varf=78.685;

      cout << (int) varf;

}

In the above program, variable varf is declared as a float with an initial value 78.685. The value of varf is explicitly converted to an int type in cout statement. Thus, the final output will be 78.

During explicit conversion, if you assign a value to a type with a greater range, it does not cause any problem. But, assigning a value of a larger type to a smaller type may result in loosing or loss of precision values.


Table 9.12 – Explicit Conversion Problems

Example:

#include <iostream>

using namespace std;

int main()

{

double varf=178.25255685;

cout << (float) varf << endl;

cout << (int) varf << endl;

}

 

Output:

178.253

178

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 9 : Introduction to C++ : C++: Type Conversion |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.