Lecture 19: Defining new types |
Type typename = description; |
with typename the name we want to give to the type and decription any type of variable we have learned until now, including arrays, records and all the simple variable types. It can also be of the type pointer which we will learn in the next lesson.
Examples:
Type float = real;
This is useful for people that are used to programming
in C. After writing the line above, we can use variables of type float,
just like in C.
Type realarray = array[1..10] of real;
Type myrecord =
record
name: string;
length: real;
width: real;
height: real;
end;
Note that this definition of a new type does not create
a variable! It does not save space in memory and it does not assign
a name to a variable. It is just a description of a type that we can use
later in declaring a variable.
Var varname: typename; |
with varname the name of a new variable and the type of this variable is typename, as decribed before. After the declaration we can use the variable as if it were declared in the normal way.
Examples:
Var f: float;
This looks already much more like C (in C
it would be "float f")
Var ra: realarray;
And in the code we can use this array:
ra[1] := 2.68;
This is completely equivalent with
Var ra: array[1..10] of real;
ra[1] := 2.68;
The last example
Type myrecord =
record
name: string;
length: real;
width: real;
height: real;
end;
Var mydata: array[1..100] of myrecord;
mydata[23].length := 3.1;
Type ra = array[1..6]
of integer;
Var x: ra;
y: array[1..7]
of integer;
FUNCTION AreEqual(r: ra): boolean;
(* Note that the definition can also
be used for parameters *)
begin
if r[1]=r[2] then
AreEqual := TRUE;
else
AreEqual := FALSE;
end;
begin
x[1] := 1;
x[2] := 0;
WriteLn(AreEqual(x));
y[1] := 1;
y[2] := 0;
(* The following line of code
is not allowed because the type of y and the type the function 'AreEqual'
expects are different. Look at the size of the arrays. *)
WriteLn(AreEqual(y));
end.
Type time =
record
hour, minute, second:
integer;
end;
PROCEDURE ShowTime(t: time);
(* Will show the time in format h:m:s
*)
begin
WriteLn(t.hour, ':', t.minute, '.',
t.second);
end;
Var atime: time;
begin
atime.hour := 23;
atime.minute := 16;
atime.second := 9;
ShowTime(atime);
end.
Type date =
record
day, month, year: integer;
end;
Type time =
record
hour, minute, second:
integer;
end;
Type dateandtime =
record
dattime: time;
datdate: date;
end;
Var x: datendtime;
x.dattime.hour := 1;
x is a record
containing two fields. One field is dattime
which is a record of three fields. One of these fields is hour.