In
computer science
Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
, type conversion,
type casting,
type coercion,
and type juggling are different ways of changing an
expression
Expression may refer to:
Linguistics
* Expression (linguistics), a word, phrase, or sentence
* Fixed expression, a form of words with a specific meaning
* Idiom, a type of fixed expression
* Metaphorical expression, a particular word, phrase, o ...
from one
data type
In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
to another. An example would be the conversion of an
integer
An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign (−1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the language ...
value into a
floating point
In computing, floating-point arithmetic (FP) is arithmetic that represents real numbers approximately, using an integer with a fixed precision, called the significand, scaled by an integer exponent of a fixed base. For example, 12.345 can be ...
value or its textual representation as a
string
String or strings may refer to:
*String (structure), a long flexible structure made from threads twisted together, which is used to tie, bind, or hang other objects
Arts, entertainment, and media Films
* ''Strings'' (1991 film), a Canadian anim ...
, and vice versa. Type conversions can take advantage of certain features of
type hierarchies or
data representation
Data and information visualization (data viz or info viz) is an interdisciplinary field that deals with the graphic representation of data and information. It is a particularly efficient way of communicating when the data or information is num ...
s. Two important aspects of a type conversion are whether it happens ''implicitly'' (automatically) or ''explicitly'',
and whether the underlying data representation is converted from one representation into another, or a given representation is merely ''reinterpreted'' as the representation of another data type.
In general, both
primitive and
compound data type
In computer science, a composite data type or compound data type is any data type which can be constructed in a program using the programming language's primitive data types and other composite types. It is sometimes called a structure or aggre ...
s can be converted.
Each
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
has its own rules on how types can be converted. Languages with
strong typing
In computer programming, one of the many ways that programming languages are colloquially classified is whether the language's type system makes it strongly typed or weakly typed (loosely typed). However, there is no precise technical definition o ...
typically do little implicit conversion and discourage the reinterpretation of representations, while languages with
weak typing
In computer programming, one of the many ways that programming languages are colloquially classified is whether the language's type system makes it strongly typed or weakly typed (loosely typed). However, there is no precise technical definition o ...
perform many implicit conversions between data types. Weak typing language often allow forcing the
compiler
In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
to arbitrarily interpret a data item as having different representations—this can be a non-obvious programming error, or a technical method to directly deal with underlying hardware.
In most languages, the word ''coercion'' is used to denote an ''implicit'' conversion, either during compilation or during
run time
Run(s) or RUN may refer to:
Places
* Run (island), one of the Banda Islands in Indonesia
* Run (stream), a stream in the Dutch province of North Brabant
People
* Run (rapper), Joseph Simmons, now known as "Reverend Run", from the hip-hop group ...
. For example, in an expression mixing integer and floating point numbers (like 5 + 0.1), the compiler will automatically convert integer representation into floating point representation so fractions are not lost. Explicit type conversions are either indicated by writing additional code (e.g. adding type identifiers or calling built-in
routines) or by coding conversion routines for the compiler to use when it otherwise would halt with a type mismatch.
In most
ALGOL
ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
-like languages, such as
Pascal
Pascal, Pascal's or PASCAL may refer to:
People and fictional characters
* Pascal (given name), including a list of people with the name
* Pascal (surname), including a list of people and fictional characters with the name
** Blaise Pascal, Fren ...
,
Modula-2
Modula-2 is a structured, procedural programming language developed between 1977 and 1985/8 by Niklaus Wirth at ETH Zurich. It was created as the language for the operating system and application software of the Lilith personal workstation. It w ...
,
Ada
Ada may refer to:
Places
Africa
* Ada Foah, a town in Ghana
* Ada (Ghana parliament constituency)
* Ada, Osun, a town in Nigeria
Asia
* Ada, Urmia, a village in West Azerbaijan Province, Iran
* Ada, Karaman, a village in Karaman Province, Tur ...
and
Delphi
Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient classical world. The oracle ...
, ''conversion'' and ''casting'' are distinctly different concepts. In these languages, ''conversion'' refers to either implicitly or explicitly changing a value from one data type storage format to another, e.g. a 16-bit integer to a 32-bit integer. The storage needs may change as a result of the conversion, including a possible loss of precision or truncation. 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 4-byte string, an unsigned 32-bit integer or an IEEE single precision floating point value. Because the stored bits are never changed, the programmer must know low level details such as representation format, byte order, and alignment needs, to meaningfully cast.
In the C family of languages and
ALGOL 68
ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously de ...
, the word ''cast'' typically refers to an ''explicit'' type conversion (as opposed to an implicit conversion), causing some ambiguity about whether this is a re-interpretation of a bit-pattern or a real data representation conversion. More important is the multitude of ways and rules that apply to what data type (or class) is located by a pointer and how a pointer may be adjusted by the compiler in cases like object (class) inheritance.
Language comparison
C-like languages
Implicit type conversion
Implicit type conversion, also known as ''coercion'' or ''type juggling'', is an automatic type conversion by the
compiler
In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
. Some
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
s allow compilers to provide coercion; others require it.
In a mixed-type expression, data of one or more
subtype
Subtype may refer to:
* Viral subtypes, such as Subtypes of HIV
* Subtyping
In programming language theory, subtyping (also subtype polymorphism or inclusion polymorphism) is a form of type polymorphism in which a subtype is a datatype that is ...
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
C (''pronounced like the letter c'') is a general-purpose computer programming language. It was created in the 1970s by Dennis Ritchie, and remains very widely used and influential. By design, C's features cleanly reflect the capabilities o ...
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
In the social sciences, unintended consequences (sometimes unanticipated consequences or unforeseen consequences) are outcomes of a purposeful action that are not intended or foreseen. The term was popularised in the twentieth century by Ameri ...
can arise. Data can be lost when converting representations from floating-point to integer, as the fractional components of the floating-point values will be truncated (rounded toward zero). Conversely, precision can be lost when converting representations from integer to floating-point, since a floating-point type may be unable to exactly represent an integer type. For example, might be an
IEEE 754
The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point arithmetic established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE). The standard addressed many problems found i ...
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:
#include
int main(void)
On compilers that implement floats as IEEE single precision, and ints as at least 32 bits, this code will give this peculiar print-out:
The integer is: 16777217
The float is: 16777216.000000
Their equality: 1
Note that 1 represents equality in the last line above. This odd behavior is caused by an implicit conversion of to float when it is compared with . The conversion causes loss of precision, which makes the values equal before the comparison.
Important takeaways:
# to causes
truncation
In mathematics and computer science, truncation is limiting the number of digits right of the decimal point.
Truncation and floor function
Truncation of positive real numbers can be done using the floor function. Given a number x \in \mathbb ...
, i.e., removal of the fractional part.
# to causes rounding of digit.
# to causes dropping of excess higher order bits.
=Type promotion
=
One special case of implicit type conversion is type promotion, where an object is automatically converted into another data type representing a
superset
In mathematics, set ''A'' is a subset of a set ''B'' if all elements of ''A'' are also elements of ''B''; ''B'' is then a superset of ''A''. It is possible for ''A'' and ''B'' to be equal; if they are unequal, then ''A'' is a proper subset of ...
of the original type. Promotions are commonly used with types smaller than the native type of the target platform's
arithmetic logic unit
In computing, an arithmetic logic unit (ALU) is a Combinational logic, combinational digital circuit that performs arithmetic and bitwise operations on integer binary numbers. This is in contrast to a floating-point unit (FPU), which operates on ...
(ALU), before arithmetic and logical operations, 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.
In
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
:
int x = 3;
double y = 3.5;
System.out.println(x + y); // The output will be 6.5
Explicit type conversion
Explicit type conversion, also called type casting, is a type conversion which is explicitly defined within a program (instead of being done automatically according to the rules of the language for implicit type conversion). It is defined by the user in the program.
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 with "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
In signal processing and related disciplines, aliasing is an effect that causes different signals to become indistinguishable (or ''aliases'' of one another) when sampled. It also often refers to the distortion or artifact that results when a ...
.
In
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pr ...
languages, objects can also be
downcast : a reference of a base class is cast to one of its derived classes.
C# and 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
In
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
a similar effect can be achieved using ''C++-style cast syntax''.
Animal* animal = new Cat;
Bulldog* b = static_cast(animal); // compiles only if either Animal or Bulldog is derived from the other (or same)
b = dynamic_cast(animal); // if (animal is Bulldog), b = (Bulldog*) animal, else b = nullptr
Bulldog& br = static_cast(*animal); // same as above, but an exception will be thrown if a nullptr was to be returned
// this is not seen in code where exception handling is avoided
animal = nullptr;
b = dynamic_cast(animal); // b nullptr
delete animal; // always free resources
Eiffel
In
Eiffel
Eiffel may refer to:
Places
* Eiffel Peak, a summit in Alberta, Canada
* Champ de Mars – Tour Eiffel station, Paris, France; a transit station
Structures
* Eiffel Tower, in Paris, France, designed by Gustave Eiffel
* Eiffel Bridge, Ungheni, M ...
the notion of type conversion is integrated into the rules of the type system. The Assignment Rule says that an assignment, such as:
x := y
is valid if and only if the type of its source expression,
y
in this case, is ''compatible with'' the type of its target entity,
x
in this case. In this rule, ''compatible with'' means that the type of the source expression either ''conforms to'' or ''converts to'' that of the target. Conformance of types is defined by the familiar rules for
polymorphism in object-oriented programming
In programming language theory and type theory, polymorphism is the provision of a single interface to entities of different types or the use of a single symbol to represent multiple different types.: "Polymorphic types are types whose operati ...
. For example, in the assignment above, the type of
y
conforms to the type of
x
if the class upon which
y
is based is a descendant of that upon which
x
is based.
Definition of type conversion in Eiffel
The actions of type conversion in Eiffel, specifically ''converts to'' and ''converts from'' are defined as:
A type based on a class CU ''converts to'' a type T based on a class CT (and T ''converts from'' U) if either
:CT has a ''conversion procedure'' using U as a conversion type, or
:CU has a ''conversion query'' listing T as a conversion type
Example
Eiffel is a fully compliant
language
Language is a structured system of communication. The structure of a language is its grammar and the free components are its vocabulary. Languages are the primary means by which humans communicate, and may be conveyed through a variety of met ...
for Microsoft
.NET Framework
The .NET Framework (pronounced as "''dot net"'') is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. It was the predominant implementation of the Common Language Infrastructure (CLI) until bein ...
. Before development of .NET, Eiffel already had extensive class libraries. Using the .NET type libraries, particularly with commonly used types such as strings, poses a conversion problem. Existing Eiffel software uses the string classes (such as
STRING_8
) from the Eiffel libraries, but Eiffel software written for .NET must use the .NET string class (
System.String
) in many cases, for example when calling .NET methods which expect items of the .NET type to be passed as arguments. So, the conversion of these types back and forth needs to be as seamless as possible.
my_string: STRING_8 -- Native Eiffel string
my_system_string: SYSTEM_STRING -- Native .NET string
...
my_string := my_system_string
In the code above, two strings are declared, one of each different type (
SYSTEM_STRING
is the Eiffel compliant alias for System.String). Because
System.String
does not conform to
STRING_8
, then the assignment above is valid only if
System.String
converts to
STRING_8
.
The Eiffel class
STRING_8
has a conversion procedure
make_from_cil
for objects of type
System.String
. Conversion procedures are also always designated as creation procedures (similar to constructors). The following is an excerpt from the
STRING_8
class:
class STRING_8
...
create
make_from_cil
...
convert
make_from_cil ()
...
The presence of the conversion procedure makes the assignment:
my_string := my_system_string
semantically equivalent to:
create my_string.make_from_cil (my_system_string)
in which
my_string
is constructed as a new object of type
STRING_8
with content equivalent to that of
my_system_string
.
To handle an assignment with original source and target reversed:
my_system_string := my_string
the class
STRING_8
also contains a conversion query
to_cil
which will produce a
System.String
from an instance of
STRING_8
.
class STRING_8
...
create
make_from_cil
...
convert
make_from_cil ()
to_cil:
...
The assignment:
my_system_string := my_string
then, becomes equivalent to:
my_system_string := my_string.to_cil
In Eiffel, the setup for type conversion is included in the class code, but then appears to happen as automatically as
explicit type conversion in client code. The includes not just assignments but other types of attachments as well, such as argument (parameter) substitution.
Rust
Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH ...
provides no implicit type conversion (coercion) between primitive types. But, explicit type conversion (casting) can be performed using the
as
keyword.
println!("1000 as a u16 is: ", 1000 as u16);
Security issues
In
hacking, typecasting is the misuse of type conversion to temporarily change a
variable
Variable may refer to:
* Variable (computer science), a symbolic name associated with a value and whose associated value may be changed
* Variable (mathematics), a symbol that represents a quantity in a mathematical expression, as used in many ...
's data type from how it was originally defined. This provides opportunities for hackers since in type conversion after a variable is "typecast" to become a different data type, the compiler will treat that hacked variable as the new data type for that specific operation.
[Arpita Gopal ''Magnifying C'' 2009 8120338618 p. 59 "From the above, it is clear that the usage of typecasting is to make a variable of one type, act like another type for one single operation. So by using this ability of typecasting it is possible for create ASCII characters by typecasting integer to its ..."]
See also
*
Downcasting
In class-based programming, downcasting or type refinement is the act of casting a reference of a base class to one of its derived classes.
In many programming languages, it is possible to check through type introspection to determine whether the ...
*
Run-time type information#dynamic cast and Java cast
*
Type punning
In computer science, a type punning is any programming technique that subverts or circumvents the type system of a programming language in order to achieve an effect that would be difficult or impossible to achieve within the bounds of the formal ...
References
External links
Casting in Ada*
Casting in C++
C++ Reference GuideWhy I hate C++ Cast Operators, by Danny Kalev
Implicit Conversions in C#Implicit Type Casting at Cppreference.com*
Upcasting and Downcasting in F#
{{DEFAULTSORT:Type Conversion
Data types
Operators (programming)
Type theory
Unary operations