Type conversion

From Wikipedia, the free encyclopedia

(Redirected from Cast (computer science))
Jump to: navigation, search
For other meanings, see typecasting.

In computer science, type conversion or typecasting refers to changing an entity of one data type 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.

Contents

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

In a mixed-type expression, data of one or more subtypes 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;
if (d == l)     d *= 2;

Although d, l and i belong to different data types, they will be automatically converted to equal data types each time a comparison or assignment is executed. This behavior should be used with caution, as unintended consequences can arise. Data can 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, since the floating-point type may be unable to represent the integer exactly (for example, float might be an IEEE 754 single precision type, which cannot represent the integer 16777217 exactly, while a 32-bit integer type can). This can lead to situations such as storing the same integer value into two variables of type int and type single which return false if compared for equality.

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 performed. 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. This can also be achieved via aliasing.

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 C++ the static_cast operator changes expressions of one static type to objects and values of another static type.

 static_cast (object);

The type parameter must be a data type for which there is a known method for converting object to, whether this be a builtin or through a casting function. It can be a reference or an enumerator.

The static_cast operator can be used for operations such as

  • Converting a pointer to a base class to a pointer to a derived class,
  • Convert numeric data types such as enums to ints or ints to floats.

However, static_cast conversions are not necessarily safe as no run-time type check is done which can cause casting between incompatible data types, for example pointers. However, this is checked at compile time to prevent casting obviously incompatibles. Also, sometimes static_cast between pointer to base to pointer to derived will produce an erroneous result, because of the object layout model.

The Eiffel programming language has a full-fledged conversion mechanism [1]enabling any type to define conversions to and from any other type. Unlike C-style casting mechanisms it is designed to be type-safe.

The mechanism generalizes to arbitrary types the conventions applied by most programming languages to automatic conversions between arithmetic types, for example INTEGER to REAL. Since these types are themselves defined by classes, the conversions between them are not language-defined "magic" but specified in the corresponding classes as they would be for any other types.

The basic idea is that a creation procedure (constructor) can be specified as being also a conversion procedure. For example a DATE class may have the form

 class DATE create
    make_from_tuple, ... other creation procedures ...
 convert
    make_from_tuple
 feature
    ...
    make_from_tuple (t: TUPLE [day:NATURAL; month: STRING, year: NATURAL])
        do
          ... Instructions to initialize the fields of the current
              object from day, month and year ...
        end
  ...

end

Then it is possible to create a DATE object through a normal creation procedure

  create my_date.make_from_tuple ([1, "January", 2000])
        -- where [a, b, c], denotes a tuple with the given values

but because make_from_tuple is also specified as a conversion procedure, a plain assignment will also do, with the same effect:

  my_date := [1, "January", 2000]

or in a call

  routine_expecting_a_date_argument ([1, "January", 2000])

The mechanism can be used to define conversions not only from tuples as in this example but between any two classes, for example

 class REAL create
     make_from_integer
 convert
     make_from_integer
 feature
     make_from_integer (n: INTEGER) do ... end
 ...
 end

This technique assumes that the programmer has control over the text of the target class (DATE and REAL in these examples). If this is not the case, it is possible to define a creation function (instead of a creation procedure) in the source class.

The key principles, to guarantee safety and clarity of the mechanism, are that

  • It is not permitted to have a conversion procedure from A to B and a conversion function from B to A (as this would make assignments such as the above ambiguous).
  • If B conforms to A -- meaning it is a subtype, e.g. B is a class that inherits from class A -- then it is not permitted to have B also convert to A.

Wikibooks
Wikibooks' Transwiki has more about this subject:

  1. ^ Meyer B.: Conversions in an Object-Oriented Language with Inheritance, in JOOP (Journal of Object-Oriented Programming), vol. 13, no. 9, January 2001, pages 28-31.

Advanced Search
Included Web Search Engines


Safe Search

close

Top Matching Results

Occasionally Search.com will highlight specialized results that are based on the context of your query. Examples of specialized results include specific links to news, images, or video.

Top Matching Results may highlight information from other Search.com pages, content from the CNET Network of sites, or third party content. The listings are based purely on relevance. Search.com does not receive payment for listings in this section but our partners that provide this data may get paid for listing these products.

Sponsored Links

This section contains paid listings which have been purchased by companies that want to have their sites appear for specific search terms and related content. These listings are administered, sorted and maintained by a third party and are not endorsed by Search.com.

Search Results

Search.com sends your search query to several search engines at one time and integrates the results into one list which has been sorted by relevance using Search.com's proprietary algorithm. You can customize the list of search engines included in your metasearch from the preferences.

The search engines that are used in your metasearch may allow companies to pay to have their Web sites included within the results. To view the Paid Inclusion policy for a specific search engine, please visit their Web site. Search.com does not accept payment or share revenue with any search engine partner for listings in this section.