Suppose you want to hold the values of a number of persons in a file or temporary. The features of the persons like age, sex, ID number. One way could be to have three arrays of size number of persons and store their values in the respective indexes. This would be very complex to code and remember and the resulting code would not be very readable. For such problems, Pascal has the keyword RECORD . Records have several fields you can specify. The general structure is
type |
record typename = record |
feature-1 : type-1; |
feature-2 : type-2; |
feature-n : type-n; |
end; |
An example could be
person = record |
age:integer; |
sex:char; |
IDno:integer; |
end; |
This is written in the type declaration part of your code, then you can declare variables of type person in the variable declaration part. Suppose you have a variable per1 of this type. You can use the single fields of the record by referencing to them as per1.age, per1.sex and per1.idno. You can write them as you do ordinary variables and use them like these. You can also use them in case statements. An example could be
case per1.sex of |
'F' : writeln(female); |
'M' : writeln('male') |
end; |
You can also declare files of records. Refer to the I/O and Files section.
The with Statement
If you get tired of writing 'per1.' and you have to use it in a sequence of statements, then you can use the with statement. It's general format is:
with record-variable do |
statement |
Lets have the previous example with a with statement:
with per1 do |
case sex of |
'F ' : writeln('female'); |
'M' : writeln('male') |
end; |
As you see you don't have to write per1.sex anymore, sex is enough if it is within a with-block.