|
|
|
|
|
by kazinator
340 days ago
|
|
In C, cast converts a value to another type (or a more or less qualified version of the same type). What that conversion means depends on the source and destination type. A cast of insert a conversion that wouldn't take place: 1/2 vs 1/(double)2
or coerce a conversion that otherwise requires a diagnostic: bar *b = 0;
foo *f = (foo *) b;
Loosely speaking, casting is another name for coercion, which refers to making a conversion happen that might not otherwise. |
|
Because I'm tired, and this is a very basic topic, I'm afraid I'm just going to rip from Wikipedia:
> In most ALGOL-like languages, such as Pascal, Modula-2, Ada and Delphi, 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, 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.