Conversions

Wednesday, 10 July 2013
TYPE CONVERSION IN C++
What is Type Conversion
It is the process of converting one type into another. In other words converting an expression of a given type into another is called type casting.
How to achieve this
There are two ways of achieving the type conversion namely:
Automatic Conversion otherwise called as Implicit Conversion
Type casting otherwise called as Explicit Conversion
Let us see each of these in detail:
Automatic Conversion otherwise called as Implicit Conversion
This is not done by any conversions or operators. In other words value gets automatically converted to the specific type in which it is assigned.
Let us see this with an example:

#include <iostream.h>
void main ()
{
short x=6000;
int y;
y=a;
}
In the above example the data type short namely variable x is converted to int and is assigned to the integer variable y.
So as above it is possible to convert short to int, int to float and so on.
Type casting otherwise called as Explicit Conversion
Explicit conversion can be done using type cast operator and the general syntax for doing this is
Data type (expression);
Here in the above data type is the type which the programmer wants the expression to gets changed as
In C++ the type casting can be done in either of the two ways mentioned below namely:

C-style casting
C++-style casting
The C-style casting takes the syntax as
(Type) expression
This can also be used in C++.
Apart from the above the other form of type casting that can be used specifically in C++ programming language namely C++-style casting is as below namely:
Type (expression)
This approach was adopted since it provided more clarity to the C++ programmers rather than the C-style casting.
Say for instance the as per C-style casting
(Type) first Variable * second Variable
Is not clear but when a programmer uses the C++ style casting it is much more clearer as below
Type (first Variable) * second Variable
Let us see the concept of type casting in C++ with a small example:
#include <iost ream.h>
void main()
{
int a;
float b, c;
cout<< “Enter the value of a:”;
cin>>a;
cout<< “\n Enter the value of b:”;
cin>>b;
c = float(a)+b;
cout<<”\n The value of c is:”<<c;
}
The output of the above program is
Enter the value of a: 10
Enter the value of b: 12.5
the value of c is: 22.5
In the above program is declared as integer and b and c are declared as float. In the type conversion statement namely
c = float (a) +b;
The variable a of type integer is converted into float type and so the value 10 is converted as 10.0 and then is added with the float variable b with value 12.5 giving a resultant float variable c with value as 22.5

No comments:

Post a Comment