C++ - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Type Casting in C++

Type Casting in C++

shape Description

CPP supports Type Casting. Type Casting in CPP is a process that converts a variable from one type to another type. The compiler takes the latest data type for that particular variable when Type Casting is applied on the variable .

shape Example

[c]int x; x=(float)8/3; [/c] In the above example, first the variable x is in integer type and then converted to float type. Two types of type-casting are available.They are

Implicit Type Conversion

shape Description

The compiler performs the automatic conversion of type and hence it is called as Implicit Conversion or Type Promotion. The variable to be converted always appears on the left side of arithmetic operator. The data type of highest operand is given to all the operands. No data is lost when implicit conversion is used. Implicit conversion focuses mainly on conversion from "low data type to high data type".

shape Conceptual figure

shape Example

[c] int a; float b,c; c=a+b; // int is converted to float[/c]

Explicit Type Conversion

shape Description

The developer performs the Explicit Type of Conversion. The conversion focuses mainly on conversion from "high data type to low data type". Data is lost when used explicit conversion. Explicit Type casting in C is done in the following way.
(data_type)expression;
where, data_type is any valid c data type, and expression may be constant, an expression or a variable. To avoid the loss of information while performing the explicit conversions following rules have to be followed.

shape Examples

[c] float a=1.23; int b=(int)a;[/c] In the above example, float value is 1.23. When float is converted to integer data type, only '1' is the output. The remaining '0.23' is lost due to explicit conversion.

shape Example

[c] #include<iostream> using namespace std; int main() { int i=20; short p; p = (short) i; // Explicit conversion cout << "Explicit value is "<< p ; }[/c] Output: [c] Explicit value is 20[/c]

Summary

shape Key Points

Type Casting in CPP chapter draws out following important points.
  • Type Casting in CPP helps in conversion of variable type
  • Implicit conversion is performed from low data type to high data type and Explicit conversion functions in reverse to implicit.

shape Programming Tips

When a result is assigned to variable of different type, there may be a loss of data during conversion.