What is value typecasting in Pascal?
Typecasting a variable means converting a variable from one datatype to another. There are two types of typecasting in Pascal:
- Implicit typecasting: Typecasting in which the range of the source data type is less than the range of the destination data type is called implicit typecasting.
- Explicit typecasting: Typecasting in which the range of the source data type is greater than the range of the destination data type is called explicit typecasting.
There are two types of explicit typecasting:
Value typecasting
Value typecasting converts the value of a data type to another data type. The value typecasting of a variable can be done as follows:
_newDatatype_(_value_)
_newDatatype_: The datatype in which_value_will be converted._value_: The value to be converted into the datatype_newDatatype_.
Note: The
_value_can be a variable or an expression.
Value typecasting vs variable typecasting
We cannot use value typecasting on the left side of assignment. On the other hand, we can use variable typecasting on both sides of assignment.
Code
Example 1
Consider the code snippet below, which demonstrates the use of value typecasting.
program Example1;varch1: Char = 'a';beginwriteln('');writeln('a typecased as integer: ', Integer(ch1));writeln('a typecased as byte: ', Byte(ch1));end.
Explanation
A character ch1 is typecasted to an integer and a byte.
Example 2
Consider the code snippet below, which demonstrates the type casting of integer to other data types.
program Example2;varnum1: Integer = 99;beginwriteln('99 typecased as char: ', Char(num1));writeln('99 typecased as bool: ', Boolean(num1));end.
Explanation
An integer num1 is typecasted to a character and a boolean value.
Free Resources