What is variable typecasting in Pascal?
Typecasting a variable means converting a variable from one data type to another. There are two types of typecasting in Pascal:
- Implicit typecasting: Typecasting in which the range of values of the source data type is less than the range of values of the destination data type is called implicit typecasting.
- Explicit typecasting: Typecasting in which the range of values of the source data type is greater than the range of values of the destination data type is called explicit typecasting.
Variable typecasting
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.
Variable typecasting vs value typecasting
We can use variable typecasting on both sides of the assignment operator. We cannot use value typecasting on the left side of an assignment.
Code
Example 1
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.
Explanation
- Line 7: A character
ch1is typecased to an integernum1. - Line 10: An integer
num1is typecased to a characterch1.
Example 2
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.
Explanation
- Line 7: A byte
ch2is typecased to a characterch1. - Line 10: A character
ch1is typecased to a bytech2.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved