Type

From Free Pascal wiki
Jump to navigationJump to search

Deutsch (de) English (en) suomi (fi) français (fr) русский (ru)

The reserved word type is used to:

  • start sections for user defined types, and
  • identify a new type instance when referring to another data type.

custom type definitions

type starts a section, where the programmer may associate identifiers with new data types, especially structured data types such as records.

program typeDemo(input, output, stderr);

type
	atom = record
		electrons: longword;
		neutrons: longword;
		protons: longword;
	end;

var
	x: atom;

begin
	x.protons := 1; // H
	x.neutrons := 1; // D
	x.electrons := 1; // 0
end.

type aliases

In a type section aliases to already existing or previously defined data types can be declared. The following example utilizes conditional compilation to alias the largest available unsigned integer type as wholeNumber (note there is already system.nativeUInt defined).

program typeAliasDemo(input, output, stderr);

type
	wholeNumber =
		{$ifdef CPU64}
			qword
		{$else}
			{$ifdef CPU32}
				longword
			{$else}
				{$fatal whole number too small}
			{$endif}
		{$endif}
		;

begin
end.

type clone

In a type section a type identifier preceded by the word type actually clones the type, with its type information, but creating different types. Nontheless, these types are still assigment compatible, which is a unique feature of the FPC (e. g. Delphi does not allow this assignment).

program typeCloneDemo(input, output, stderr);

type
  wholeNumber = type qword;

var
  A: qword;
  B: wholeNumber;

begin
  writeLn('qword:       ', sysBackTraceStr(typeInfo(qword)));
  writeLn('wholeNumber: ', sysBackTraceStr(typeInfo(wholeNumber)));

  A := 3;
  B := A;
end.

You want to do this, for instance in order to define a whole new set of operators. Otherwise the operator definitions for the type it was cloned from would still apply.

see also