3.7. Typecasting


What is typecasting?

Typecasting is pretending that a variable of one type is actually of another type (this isn't a formal definition). For example, a boolean variable could be typecast to a byte, which would allow the data in the variable to be treated as a number. You might want to do this if you wanted to add 1 to a number if a boolean variable is true, in which case you can just add the byte version of the variable.

To typecast a variable in Pascal, use the type you want to typecast to as if it were a function e.g. byte(a_boolean_var) returns the data in the variable a_boolean_var as if it were a byte. Turbo Pascal won't let you just typecast anything to anything; it has some rules, one of which is that the data type and the data must have the data size. It will also sometimes do some automatic conversion, for example if you typecast an integer to a longint, it will actually convert the integer into a longint.


Why use typecasting?

Typecasting is only useful if you know something about the way different types are stored internally. For example, a boolean is a byte that contains 1 for true or 0 for false, or a char is a byte containing the ASCII code of the character. Usually you use typecasting to access the data in a variable in a different way.

A good example is typecasting an integer to a set. A set with the range 0 to 15 (note that it must start at 0 because of the way Turbo Pascal deals with sets) is a 2 byte integer with each bit representing one element's presence or absence. Thus if an integer is put in a loop from 0 to 65535 (use a word, because 65535 is too big for an integer) and typecast to a set of this type inside the loop, then the set will loop through all subsets of the set 0..15!


Another way to typecast

Sometimes Turbo Pascal doesn't allow you to do a typecast that it thinks doesn't make sense. If you know what you are doing, you can work around it with the absolute keyword. When declaring a variable followed by this keyword and the name of another variable, the compiler will make the two variables point to the same block of memory if it can. For example:

var
   aset : set of 0..15;
   aword : word absolute aset;

Here the two variables use the same two bytes of memory.


[Prev] [Next] [Up]

Last updated Sun Nov 28 22:04:38.0000000000 2004. Copyright Bruce Merry (bmerry '@' gmail dot. com).