Typecasting a variable means converting a variable from one data type to another. There are two types of typecasting in Pascal:
Variable typecasting temporarily converts the data type of a variable. It does not change the contents of the variable. The variable typecasting of a variable can be done as follows:
_newDatatype_(_variable_)
_newDatatype_
: The datatype in which _variable_
will be converted._variable_
: The variable to be converted into the datatype _newDatatype_
.Note: Variable typecasting works on the variables whose addresses we can take.
We can use variable typecasting on both sides of the assignment operator. We cannot use value typecasting on the left side of an assignment.
Consider the code snippet below, which demonstrates the use of variable typecasting.
program Example1;varch1: Char = 'a';num1: Integer = 10;beginwriteln('');num1 := Integer(ch1);writeln('a typecased as integer: ', num1);ch1 := Char(num1);writeln('97 typecased as character: ', ch1);end.
ch1
is typecased to an integer num1
.num1
is typecased to a character ch1
.Consider the code snippet below, which demonstrates variable typecasting on the left side of an assignment.
program Example2;varch1: Char = 'a';ch2: Byte;beginwriteln('');Char(ch2) := ch1;writeln('byte typecased as char: ',ch2);Byte(ch1) := ch2;writeln('char typecased as byte: ',ch1);end.
ch2
is typecased to a character ch1
.ch1
is typecased to a byte ch2
.