Typecasting

Default Image

The process of converting one type data
into another type is called type casting. This conversion can be done by
default with the help of translator programme (in case of C++ it is
done by compiler) or by the programmer. The question raised why we need
such type of conversion? Some time we require to use our float type
variable sunup with integer type variable. After addition the result we
will get belongs to some data type, which data type if it is decided by
compiler this conversion will be called implicit type casting and if it is done by the user this will be called explicit.

Implicit typecasting


Every compiler uses automatic
typecasting. It automatically converts one type into another type. If
the compiler converts a type it will normally give a warning. For
example, this warning: conversion from ‘double’ to ‘int’, possible loss
of data. The problem with this is, that you get a warning (normally you
want to compile without warnings and errors) and you are not in control.
With control we mean, you did not decide to convert to another type,
the compiler did. Also, the possible loss of data could be unwanted.


Explicit typecasting


The C and C++ languages have ways to give
you back control. This can be done with what is called an explicit
conversion. You may still lose data, but you decide when to convert to
another type and you don’t get any compiler warnings.


#include


#include


void main()


{


int a;


double b=2.55;


a = b;


cout << a << endl; //first output line


a = (int)b;


cout << a << endl; //second output line


a = int(b);


cout << a << endl; // third output line


getch();


}


The first conversion is an implicit
conversion (the compiler decides.) As explained before, the compiler
should give a warning. The second conversion is an explicit typecast, in
this case the C style explicit typecast. The third conversion is also
explicit typecast, in this case the C++ style explicit typecast.

Read Count: 3 times

Comments

No comments yet.

Leave a Comment