Lesson 16 · 16 of 20
Records · Pascal
Group related data in a Pascal record: a stationery shop's products with name, price and stock, plus functions that use them.

A `record` groups several fields, of different types, into a new type. It is declared in the `type` block: TProduct has Name, Price and Stock. By convention, Pascal type names start with T.
Each field is reached with a dot: diary.Name := 'Diary'. MakeProduct is a function that returns a complete TProduct; inside it, Result.Name, Result.Price and Result.Stock fill in its fields.
Assigning a record copies every field: diary := book makes an independent copy of the notebook, and renaming it does not affect book, which is still called Notebook.
A record is passed to a procedure like any other value. Show(const p: TProduct) takes it as const, without copying it, and prints its fields in columns with :10, :8:2 and :5. The fields are also used to work out the value of the stock.
Code · main.pas
program main;type TProduct = record Name: String; Price: Double; Stock: Integer; end;function MakeProduct(const name: String; price: Double; stock: Integer): TProduct;begin Result.Name := name; Result.Price := price; Result.Stock := stock;end;procedure Show(const p: TProduct);begin WriteLn(p.Name:10, p.Price:8:2, p.Stock:5);end;var pen, book, diary: TProduct;begin pen := MakeProduct('Pen', 1.20, 50); book := MakeProduct('Notebook', 3.75, 12); // Assigning a record copies every field. diary := book; diary.Name := 'Diary'; Show(pen); Show(book); Show(diary); WriteLn('Stock value: ', pen.Price * pen.Stock + book.Price * book.Stock:0:2);end.Output · fpc main.pas && ./main
Pen 1.20 50
Notebook 3.75 12
Diary 3.75 12
Stock value: 105.00Key points
record ... endgroups fields into a new type.- Fields are read and changed with a dot:
p.Price. - Assigning a record copies all its fields.
- Functions can take and return records.
Exercise
Add a Category: String field to TProduct, fill it in MakeProduct and print it in Show; then create an eraser at 0.60 euros with 80 in stock.