What is variant in Pascal?

Overview

A variable of variant data type in Pascal can store different data types. The type of data stored in the variant is determined at runtime. However, structured data types like record and array cannot be stored in a variant. To be able to use the variant data type, you must include the following code:

uses variants;

Example

The example below demonstrates how variants can be used:

Note: You can ignore the stdout from Free Pascal Compiler... till ...compiled, 0.0 sec. It is a bug in some versions of LD.

Program VariantExample;
uses variants;
var
primary:variant;
num:integer;
yourName:string;
doubleNum:double;
begin
num := 20;
primary:= num;
writeln('Variant as integer: ', primary);
yourName:= 'Samia Ishaque';
primary:= yourName;
writeln('Variant as a string: ', primary);
doubleNum := 2.5;
primary := doubleNum ;
writeln('Variant as a double: ', primary);
end.

Explanation

In this code, we first indicate that the program uses variants. We define the variables as we normally do. We need a variable of type variant and several other variables of varying data types to demonstrate that the variant data type can store them. Then, we begin our program and store an integer, string, and a double in the variant data type one by one. We print each time to see what is stored in the variant data type. The above code demonstrates how one can store varying data types in a variant.

VarType() function

The VarType() function in Pascal can determine the data type being stored in a variant. You can use VarType() as shown below to print the data type. You can only determine the data type by using a statement.

Program VariantExample;
uses variants;
var
primary:variant;
num:integer;
yourName:string;
doubleNum:double;
begin
num := 20;
primary:= num;
writeln('Variant: ', primary);
Case varType(primary) of
varEmpty:
Writeln('Empty');
varNull:
Writeln('Null');
varSingle:
Writeln('Datatype: Single');
varDouble:
Writeln('Datatype: Double');
varDecimal:
Writeln('Datatype: Decimal');
varCurrency:
Writeln('Datatype: Currency');
varDate:
Writeln('Datatype: Date');
varOleStr:
Writeln('Datatype: UnicodeString');
varStrArg:
Writeln('Datatype: COM-compatible string');
varString:
Writeln('Datatype: Pointer to a dynamic string');
varDispatch:
Writeln('Datatype: Pointer to an Automation object');
varBoolean:
Writeln('Datatype: Wordbool');
varVariant:
Writeln('Datatype: Variant');
varUnknown:
Writeln('Datatype: unknown');
varShortInt:
Writeln('Datatype: ShortInt');
varSmallint:
Writeln('Datatype: Smallint');
varInteger:
Writeln('Datatype: Integer');
varInt64:
Writeln('Datatype: Int64');
varByte:
Writeln('Datatype: Byte');
varWord:
Writeln('Datatype: Word');
varLongWord:
Writeln('Datatype: LongWord');
varQWord:
Writeln('Datatype: QWord');
varError:
Writeln('ERROR determining variant type');
end;
end.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved