Most modern high-level programming languages maintain some degree of information about the data they manipulate. One important piece of information is the type of any given value used by the program. By type, I mean information pertaining to how that particular data is stored and what can be done to it. For example, most languages support at least an understanding of the difference between "integer" types and "string" types. This information allows error-checking by the compiler that can reduce many silly programmer errors, like attempting to treat a string as an integer or vice versa: errors that wouldn't be caught if they were made in, say, machine language.

Sometimes, though, the language is wrong, and the programmer needs to tell the language what type a value has, even if the language already thinks it knows what type is correct. This is what typecasting is for. Typecasting accepts a value, and applies a specified type to it. Thus the name: it casts to a type.

This can be very dangerous if used inappropriately, since it can subvert a language's memory management, can corrupt data, can cause inadvertant loss of precision, and can override data hiding. It is also necessary in many languages where the type of particular value is not known until runtime, and cannot be correctly known by the language ahead of time.


In C, a typecast takes the form:

( typeexp ) valueexp

Where valueexp is an expression evaluating to the value that is to be cast, and typeexp is an expression evaluating to the type that the value is to be cast to.

For example, consider the code:

char *str = ( char * ) malloc(SIZE);
strcpy(str , "text");

The code calls malloc which will allocate SIZE bytes on the heap. The result of this call has no useful type, so we tell C that it is a "char *". We can now store this value into a variable "str" which is already of type "char *". The second line treats this variable as a normal instance of its type.

Unfortunately, typecasts are not always easy to spot in C because of the many uses of parentheses in that language.

Typecasting is a little more complicated in C++, and to deal with this situation, C++ introduces several typecasting operators: dynamic_cast, static_cast, const_cast, and reinterpret_cast.

The above is a fairly mundane example, since it only converts between pointer types. There are several more complex (and dangerous) scenarios invovling typecasting which will be covered in the C++ typecast operator nodes.