Tutorial - Introduction to Structures

A structure ( called a record in some other programming languages ) is a way of collecting together a set a related values - such as name, age and employee number. Each element in a structure can be a different data type ( including another structure type ).

Syntax of a Structure Definition

The general form of a structure definition is :-

	struct_field	:= [ Const ] type_spec identifier [ =  expression ]
	structure_def	:= Type identifier = { struct_field [[ , struct_field ]] } ;

Here are some examples :-

Type TAge = { Number years, Number months };
Type TStaffRec = { Number emp_id, Text name, TAge age };

Declaring a Structure

A variable with a structure type can be declared like any other type of variable.

	TAge myage;
	TStaffRec myrecord;

Using Structure

A structure can be treated as a single block and have a value assigned to it. When setting a value to a structure the fields should be listed between braces - the simplest way is to just list a set of values in the order in which the fields were defined.

	myage := { 25, 6 };	 [= 25 years and 6 months - ( I wish! ) =]
	myrecord := { 1001, "Robin", myage };

You could even do the following :-

	myrecord := { 1001, "Robin", { 25, 6 } };

Accessing Individual Fields

It is possible to access a specific field using the 'dot' operator.

[= change the name field =]
myrecord.name := "Fred";

If you have a nested structure you can access a nested field in a similar way.

[= change the year field within the age field =]
myrecord.age.years := 30;

Constant Fields

It is possible to flag an individual field as constant. In this case the field can be changed when the whole record changes ( providing the target is not itself flagged as constant ) but the individual field cannot be changed.

Type MyStruct = { Number id = 100, Const Text name = "Robin", Text addr };

Program()
	MyStruct myrecord;
    Begin
	[= can change name as part of record =]
	myrecord := { 101, "Bill", "10 Station Road" };
	[= cannot change constant field =]
	myrecord.name:= "William";	[= *** ERROR *** =]
    End;