Type Cast - Research Article from World of Computer Science

This encyclopedia article consists of approximately 2 pages of information about Type Cast.
Encyclopedia Article

Type Cast - Research Article from World of Computer Science

This encyclopedia article consists of approximately 2 pages of information about Type Cast.
This section contains 326 words
(approx. 2 pages at 300 words per page)

A type cast is an instruction from the programmer to the compiler for it to treat a variable or object of one type (see entry on types) as if it were of another. The "type" of a variable or object is a classification of what kind of data or real-world "thing" it represents. Type-casting is a feature mostly associated with statically-typed languages, where the compiler needs to know the type of all objects in the program before it can create the executable code.

Typically, a type-cast is indicated to the compiler like this:

  • variable = () object

where "object" is of a different type from "type a." By example, to cast from a char to an integer:

  • char a = 'a';
  • int b = (int)a;

Type-casting is potentially very dangerous because the programmer is relieving the compiler of the responsibility of ensuring that objects are being used only where and how they are supposed to be used. Because of this, the compiler still makes some checks and, depending on the language, will forbid type-casts that are outside its set of internal rules.

C and C++ have a very relaxed set of rules and will happily cast between pointers to data structures and classes that are of completely unrelated type, integers, and characters without complaint. The trouble is that the compiler will believe what it is told and if the programmer has made an error and at run-time the program tries to do the wrong thing with an object, the best that can happen is catastrophic failure.

Java has a more robust method in that not only will it forbid certain casts at compile-time, but it will also check again at run time to make sure the object can do what it has been told it can do. If it detects the wrong type of object, it can report an error that the programmer can arrange to trap rather than having the whole program die horribly.

This section contains 326 words
(approx. 2 pages at 300 words per page)
Copyrights
Gale
Type Cast from Gale. ©2005-2006 Thomson Gale, a part of the Thomson Corporation. All rights reserved.