Typecasting (programming) Articles about
Type Conversion
Website Links For
Type
 

Information About

Typecasting (programming)




In Computer Science , type conversion or '''typecasting''' refers to changing an entity of one Datatype into another. This is done to take advantage of certain features of type hierarchies. For instance, values from a more limited set, such as integers, can be stored in a more compact format and later converted to a different format enabling operations not previously possible, such as division with several decimal places' worth of accuracy. In Object-oriented programming languages, type conversion allows programs to treat objects of one type as one of their ancestor types to simplify interacting with them.

There are two types of conversion: implicit and explicit. The term for implicit type conversion is Coercion . The most common form of explicit type conversion is known as ''' Casting '''. Explicit type conversion can also be achieved with separately defined conversion routines such as an Overloaded Object Constructor .


IMPLICIT TYPE CONVERSION

Implicit type conversion, also known as coercion, is an automatic type conversion by the Compiler . Some Language s allow, or even require, compilers to provide coercion.

In a mixed-type expression, data of one or more Subtype s can be converted to a Supertype as needed at Runtime so that the program will run correctly. For example, the following is legal C Language code:

double d;
long l;
int i;

if (d > i) d = i;
if (i > l) l = i;
  • = 2;


Although ''d'', ''l'' and ''i'' belong to different datatypes, they will be automatically converted to the same datatype each time a comparison or assignment is executed. This behavior should be used with caution, as unintended consequences can arise. For example, in the above comparisons, there would be a loss of information in a conversion from type ''double'' to type ''int'' if the value of ''d'' is larger then ''i'' can hold. Data can also be lost when floating-point representations are converted to integral representations as the fractional components of the floating-point values will be truncated (rounded down). Conversely, converting from an integral representation to a floating-point one can also lose precision, as floating-point representations are generally not capable of holding integer values precisely. This can lead to situations such as storing the same integer value into two variables of type int and type double which return false if compared for equality.


EXPLICIT TYPE CONVERSION

There are several kinds of explicit conversion.

; checked : Before the conversion is performed, a runtime check is done to see if the destination type can hold the source value. If not, an error condition is raised.
; unchecked : No check is perfomed. If the destination type cannot hold the source value, the result is undefined.
; bit pattern : The data is not interpreted at all, and its raw bit representation is copied verbatim.

Each Programming Language has its own rules on how types can be converted. In general, both objects and fundamental data types can be ''converted''.


in Ada


Ada supports implicit conversion between subtypes of a base type and all three explicit conversion techniques above for moving between base types. In addition, Ada features a few related conversion mechanisms, covered in more detail in the Wikibook linked to in the sidebar, which might be worth reading even if you plan to use another programming language.


in C/C++


A cast, or ''explicit type conversion'', is special programming instruction which specifies what Data Type to treat a Variable as (or an intermediate calculation result) in a given expression.

Casting will ignore "extra" information that cannot be represented by the type being cast to (but never adds information to the type being cast). The C cast is either "unchecked" or "bit pattern".

As an example with fundamental data types, a Floating-point Number could be cast as an Integer , and any digits beyond the decimal point would be ignored. Alternatively, an integer could be cast as a float if, for example, a function call required a floating-point type (but, as noted, no information is really added: 1 would become 1.0). Note that the compiler would perform the second cast automatically via coercion, but not the first, since information would be lost. It should be noted that in certain cases sufficiently high ints will lose information when cast to a float, this is because the IEEE representations of floating-point numbers allocate certain ranges of bits towards a sign bit and an exponent.

Object casting works in a similar way. A Subclass can be cast as a parent class, where the "extra" information that makes it a subclass is ignored, and only the parts inherited from the parent are available. For example, a triangle class derived from a shape class could be cast as a shape.


Two common casting styles


There are two common casting styles, each outlined below.


C-style casting


This style of casting is used in C and Java . It follows the form:

(type)expression


C++-style casting


Several cast syntaxes are used in C++ (although C-style casting is supported as well). The function-call style follows the form:

type(expression)

This style of casting was adopted to force clarity when using casting. For example, the result of, and intention of, the C style cast

(type)firstVariable + secondVariable

may not be clear, while the same cast using C++-style casting allows more clarity:

type(firstVariable + secondVariable)
or
type(firstVariable) + secondVariable

Later in the evolution of C++, the following more explicit casts were added to the language to clarify the programmer's intent even further:

static_cast(value_to_cast)
dynamic_cast(value_to_cast)
const_cast(value_to_cast)
reinterpret_cast(value_to_cast)

Static casts converts type-compatible values. For instance the following:

double myDouble = 3.0;
int myInt = static_cast(myDouble);

converts the double-precision floating-point value myDouble (3.0) to the corresponding integer value (3). Static casts can be dangerous:

  • pYour = GimmeAnObject();

  • pv = pYour; // no cast needed.

  • p = static_cast(pYour); // MyClass had better be related to YourClass...

  • p->SomeMethod(); // ...or this might blow up in a nasty way.


Static casts on pointers or references don't verify that the pointed-to object is type-compatible to the new type.

A dynamic cast is safer than a static cast in this scenario: it is compiled by the compiler into a call to the C++ Runtime Library where a check is made to ensure legal casts. This is analogous to the casts in Java .

  • pYour = GimmeAnObject();

  • pv = pYour; // no cast needed.

  • p = dynamic_cast(pYour); // This won't blow up in the same way

  • if (p != 0)

p->SomeMethod(); // C++ guarantees p points to a MyClass

Dynamic casts on pointers return a null pointer if the cast-to value is type incompatible. Dynamic casts on a reference throw a type Exception .

A const cast casts away the Constness of an object, returning a non-const reference to the same object. This allows modifications to objects that normally would be treated read-only by the compiler and allows passing to libraries that were not designed with const correctness in mind:

  • cantTouchThis = CreateConstObject();

  • cantTouchThis->constant_value = 41; // compile-time error.

  • >(cantTouchThis)->constant_value = 42; // compiles, but who knows what happens at runtime?


The reinterpret cast is the most notorious one in C++. It allows the reinterpretation of the raw bit pattern of the value to be cast, disregarding the type system completely. For example, it allows the casting of an arbitrary integer to a pointer to an object:

  • pclass = reinterpret_cast(0xDEADBEEF); // I know what I'm doing

  • pclass->some_field = 3.14159; // very unsafe indeed


Opinions were divided when these verbose casts were introduced into the language. Detractors argued the new syntax was 'ugly', while supporters claimed that since casting is such an 'ugly' activity to begin with, it should be highlighted with an 'ugly' syntax to alert Programmer s. Another perceived advantage is the ease with which verbose casts can be located in Source Code using Programming Tools like Grep .