Type conversion
Encyclopedia
In computer science
Computer science
Computer science or computing science is the study of the theoretical foundations of information and computation and of practical techniques for their implementation and application in computer systems...

, type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type
Data type
In computer programming, a data type is a classification identifying one of various types of data, such as floating-point, integer, or Boolean, that determines the possible values for that type; the operations that can be done on values of that type; the meaning of the data; and the way values of...

 into another. This is done to take advantage of certain features of type hierarchies or type representations. One example would be small integers, which can be stored in a compact format and converted to a larger representation when used in arithmetic computations. In object-oriented programming, type conversion allows programs to treat objects of one type as one of their ancestor types to simplify interacting with them.

Each programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

 has its own rules on how types can be converted. In general, both objects and fundamental data types can be converted. In most languages, the word coercion is used to denote an implicit conversion, either during compilation or during run time. A typical example would be an expression mixing integer and floating point numbers (like 5 + 0.1), where the integers are normally converted into the latter. Explicit type conversions can either be performed via built-in routines (or a special syntax) or via separately defined conversion routines such as an overloaded object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...

 constructor
Constructor (computer science)
In object-oriented programming, a constructor in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created...

.

In most Algol-based languages with nested function
Nested function
In computer programming, a nested function is a function which is lexically encapsulated within another function. It can only be called by the enclosing function or by functions directly or indirectly nested within the same enclosing function. In other words, the scope of the nested function is...

 definitions, such as Ada, Delphi, Modula 2 and Pascal, conversion and casting are distinctly different concepts. In these languages, conversion refers to either implicitly or explicitly changing a value from one data type to another, e.g. a 16-bit integer to a 32-bit integer. The storage requirements may change as a result of the conversion. A loss of precision or truncation may also occur. The word cast, on the other hand, refers to explicitly changing the interpretation of the bit pattern representing a value from one type to another. For example 32 contiguous bits may be treated as an array of 32 booleans, a two character Unicode string, an unsigned 32-bit integer or an IEEE single precision floating point value. While the storage requirements are never changed, it still requires knowledge of low level details such as representation format, byte order, and alignment requirements in order to be meaningful.

In the C family of languages, the word cast typically refers to an explicit type conversion (as opposed to an implicit conversion), regardless of whether this is a re-interpretation of a bit-pattern or a real conversion.

Implicit type conversion

Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler
Compiler
A compiler is a computer program that transforms source code written in a programming language into another computer language...

. Some language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

s 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
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 code:


double d;
long l;
int i;

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


Although , and 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 integer representations as the fractional components of the floating-point values will be truncated (rounded towards zero). Conversely, converting from an integer 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, 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 unintuitive behavior, as demonstrated by the following code:

  1. include


int main
{
int i_value = 16777217;
float f_value = 16777217.0;
printf("The integer is: %i\n", i_value);
printf("The float is: %f\n", f_value);
printf("Their equality: %i\n", i_value f_value);
}


On compilers that implement floats as IEEE single precision, and ints as at least 32 bits, this code will give the peculiar result of printing out , followed by , then (where 1 represents equal). This odd behavior is caused by an implicit cast of to float when it is compared with ; a cast which loses precision, making the values being compared different.

Following important points:
  1. to causes truncation
    Truncation
    In mathematics and computer science, truncation is the term for limiting the number of digits right of the decimal point, by discarding the least significant ones.For example, consider the real numbersThe result would be:- Truncation and floor function :...

    , i.e. removal of the fractional part.
  2. to causes rounding of digit
  3. to causes dropping of excess higher order bits.

Type promotion

One special case of implicit type conversion is type promotion, where the compiler automatically expands the binary representation of objects of integer or floating-point types. Promotions are commonly used with types smaller than the native type of the target platform's ALU
Arithmetic logic unit
In computing, an arithmetic logic unit is a digital circuit that performs arithmetic and logical operations.The ALU is a fundamental building block of the central processing unit of a computer, and even the simplest microprocessors contain one for purposes such as maintaining timers...

 prior to arithmetic and logical operations in order to make such operations possible, or more efficient if the ALU can work with more than one type. C and C++ perform such promotion for objects of boolean, character, wide character, enumeration, and short integer types which are promoted to int, and for objects of type float, which are promoted to double. Unlike some other type conversions, promotions never lose precision or modify the value stored in the object.

Explicit type conversion

Explicit type conversion is a type conversion which is explicitly defined within a program (instead of being done by a compiler for implicit type conversion).


double da = 3.3;
double db = 3.3;
double dc = 3.4;
int result = (int)da + (int)db + (int)dc; //result 9
//if implicit conversion would be used (as if result = da + db + dc), result would be equal to 10


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 raw bit representation of the source is copied verbatim, and it is re-interpreted according to the destination type. This can also be achieved via aliasing
Aliasing (computing)
In computing, aliasing describes a situation in which a data location in memory can be accessed through different symbolic names in the program. Thus, modifying the data through one name implicitly modifies the values associated to all aliased names, which may not be expected by the programmer...

.

In object-oriented programming languages, objects can also be downcast
Downcasting
In object-oriented programming, downcasting or type refinement is the act of casting a reference of a base class to one of its derived classes....

 : a reference of a base class is cast to one of its derived classes.

Using overloaded object constructor


class Myclass {
public:
double myD;
Myclass(double d) : myD(d) {};
};

int main(int argc, char *argv[])
{
Myclass obj = 5.2; // here is the type conversion
return 0;
}

C#
In C#, type conversion can be made in a safe or unsafe (i.e. C-like) manner, the former called checked type cast.


Animal animal = new Cat;

Bulldog b = (Bulldog) animal; // if (animal is Bulldog), stat.type(animal) is Bulldog, else an exception
b = animal as Bulldog; // if (animal is Bulldog), b = (Bulldog) animal, else b = null

animal = null;
b = animal as Bulldog; // b null

External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK