Pascal Reference Guide
Pascal Reference Guide
Reference guide
Reference guide for Free Pascal, version 3.0.4
Document version 3.0.4
September 2017
1 Pascal Tokens 11
1.1 Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.2 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3 Reserved words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.3.1 Turbo Pascal reserved words . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.3.2 Object Pascal reserved words . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.3.3 Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.4 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.5 Hint directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.6 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.7 Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.8 Character strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2 Constants 20
2.1 Ordinary constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.2 Typed constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.3 Resource strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3 Types 24
3.1 Base types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.1.1 Ordinal types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Boolean types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Enumeration types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Subrange types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.1.2 Real types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.2 Character types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.2.1 Char or AnsiChar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.2.2 WideChar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.2.3 Other character types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.4 Single-byte String types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
1
CONTENTS
Short strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Ansistrings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Code page conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
RawByteString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
UTF8String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.2.5 Multi-byte String types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
UnicodeStrings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
WideStrings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.2.6 Constant strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.2.7 PChar - Null terminated strings . . . . . . . . . . . . . . . . . . . . . . . . 38
3.2.8 String sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.3 Structured Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Packed structured types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.3.1 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Static arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Dynamic arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Dynamic array Type compatibility . . . . . . . . . . . . . . . . . . . . . . . 45
Dynamic array constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Packing and unpacking an array . . . . . . . . . . . . . . . . . . . . . . . . 47
3.3.2 Record types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Record layout and size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Remarks and examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.3.3 Set types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.3.4 File types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.4 Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.5 Forward type declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.6 Procedural types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.7 Variant types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
3.7.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
3.7.2 Variants in assignments and expressions . . . . . . . . . . . . . . . . . . . . 59
3.7.3 Variants and interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.8 Type aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
3.9 Managed types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4 Variables 63
4.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.2 Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.3 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
4.4 Initialized variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
4.5 Initializing variables using default . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
2
CONTENTS
5 Objects 71
5.1 Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
5.2 Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
5.3 Class or Static fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
5.4 Constructors and destructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
5.5 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.5.1 Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5.5.2 Method invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Normal static methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Virtual methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Abstract methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Class or static methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.6 Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6 Classes 82
6.1 Class definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
6.2 Normal and static fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.2.1 Normal fields/variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.2.2 Class fields/variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.3 Class instantiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
6.4 Class destruction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
6.5 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.5.1 Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.5.2 Invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.5.3 Virtual methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.5.4 Class methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.5.5 Class constructors and destructors . . . . . . . . . . . . . . . . . . . . . . . 91
6.5.6 Static class methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6.5.7 Message methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
6.5.8 Using inherited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
6.6 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.6.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.6.2 Indexed properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
6.6.3 Array properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
6.6.4 Default properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.6.5 Published properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.6.6 Storage information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
6.6.7 Overriding properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
3
CONTENTS
7 Interfaces 106
7.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
7.2 Interface identification: A GUID . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
7.3 Interface implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
7.4 Interface delegation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
7.5 Interfaces and COM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
7.6 CORBA and other Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
7.7 Reference counting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
8 Generics 114
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
8.2 Generic type definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
8.3 Generic type specialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
8.4 Generic type restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
8.5 Delphi compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
8.5.1 Syntax elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
8.5.2 Record type restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
8.5.3 Type overloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
8.5.4 Name space considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
8.5.5 Scope considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
8.6 Type compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
8.7 Using the default intrinsic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
8.8 A word about scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
8.9 Operator overloading and generics . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
4
CONTENTS
12 Expressions 155
12.1 Expression syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
12.2 Function calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
12.3 Set constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
12.4 Value typecasts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
12.5 Variable typecasts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
12.6 Unaligned typecasts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
12.7 The @ operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
12.8 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
12.8.1 Arithmetic operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
12.8.2 Logical operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
12.8.3 Boolean operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
12.8.4 String operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
12.8.5 Set operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
12.8.6 Relational operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
12.8.7 Class operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
13 Statements 170
13.1 Simple statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
13.1.1 Assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
13.1.2 Procedure statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
13.1.3 Goto statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
13.2 Structured statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
13.2.1 Compound statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
13.2.2 The Case statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
13.2.3 The If..then..else statement . . . . . . . . . . . . . . . . . . . . . . 175
13.2.4 The For..to/downto..do statement . . . . . . . . . . . . . . . . . . . 177
13.2.5 The For..in..do statement . . . . . . . . . . . . . . . . . . . . . . . . . 178
13.2.6 The Repeat..until statement . . . . . . . . . . . . . . . . . . . . . . . 185
13.2.7 The While..do statement . . . . . . . . . . . . . . . . . . . . . . . . . . 185
5
CONTENTS
6
CONTENTS
17 Exceptions 234
17.1 The raise statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
17.2 The try...except statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
17.3 The try...finally statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
17.4 Exception handling nesting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
17.5 Exception classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
7
List of Tables
8
LIST OF TABLES
Notations
Throughout this document, we will refer to functions, types and variables with typewriter font.
Files are referred to with a sans font: filename.
Syntax diagrams
All elements of the Pascal language are explained in syntax diagrams. Syntax diagrams are like flow
charts. Reading a syntax diagram means getting from the left side to the right side, following the
arrows. When the right side of a syntax diagram is reached, and it ends with a single arrow, this
means the syntax diagram is continued on the next line. If the line ends on 2 arrows pointing to each
other, then the diagram is ended.
Syntactical elements are written like this
-
- syntactical elements are like this -
This means that both the first or second possibility are optional. Of course, all these elements can be
combined and nested.
9
LIST OF TABLES
• Easy syntax, rather verbose, yet easy to read. Ideal for teaching.
• Strongly typed.
• Procedural.
• Case insensitive.
The Turbo Pascal and Delphi Pascal compilers introduced various features in the Pascal language,
most notably easier string handling and object orientedness. The Free Pascal compiler initially emu-
lated most of Turbo Pascal and later on Delphi. It emulates these compilers in the appropriate mode
of the compiler: certain features are available only if the compiler is switched to the appropriate
mode. When required for a certain feature, the use of the -M command-line switch or {$MODE }
directive will be indicated in the text. More information about the various modes can be found in the
user’s manual and the programmer’s manual.
10
Chapter 1
Pascal Tokens
Tokens are the basic lexical building blocks of source code: they are the ’words’ of the language:
characters are combined into tokens according to the rules of the programming language. There are
five classes of tokens:
reserved words These are words which have a fixed meaning in the language. They cannot be
changed or redefined.
identifiers These are names of symbols that the programmer defines. They can be changed and
re-used. They are subject to the scope rules of the language.
operators These are usually symbols for mathematical or other operations: +, -, * and so on.
separators This is usually white-space.
constants Numerical or character constants are used to denote actual values in the source code, such
as 1 (integer constant) or 2.3 (float constant) or ’String constant’ (a string: a piece of text).
In this chapter we describe all the Pascal reserved words, as well as the various ways to denote
strings, numbers, identifiers etc.
1.1 Symbols
Free Pascal allows all characters, digits and some special character symbols in a Pascal source file.
Recognised symbols
-
- letter A...Z -
a...z
-
- digit 0...9 -
-
- hex digit 0...9 -
A...F
a...f
11
CHAPTER 1. PASCAL TOKENS
When used in a range specifier, the character pair (. is equivalent to the left square bracket [.
Likewise, the character pair .) is equivalent to the right square bracket ]. When used for comment
delimiters, the character pair (* is equivalent to the left brace { and the character pair *) is equiva-
lent to the right brace }. These character pairs retain their normal meaning in string expressions.
1.2 Comments
Comments are pieces of the source code which are completely discarded by the compiler. They exist
only for the benefit of the programmer, so he can explain certain pieces of code. For the compiler, it
is as if the comments were not present.
The following piece of code demonstrates a comment:
The use of (* and *) as comment delimiters dates from the very first days of the Pascal language. It
has been replaced mostly by the use of { and } as comment delimiters, as in the following example:
{
My beautiful function returns an interesting result,
but only if the argument A is less than B.
}
Function Beautiful (A,B : Integer): Integer;
The comment extends from the // character till the end of the line. This kind of comment was
introduced by Borland in the Delphi Pascal compiler.
Free Pascal supports the use of nested comments. The following constructs are valid comments:
12
CHAPTER 1. PASCAL TOKENS
{ Comment 1 (* comment 2 *) }
(* Comment 1 { comment 2 } *)
{ comment 1 // Comment 2 }
(* comment 1 // Comment 2 *)
// comment 1 (* comment 2 *)
// comment 1 { comment 2 }
The last two comments must be on one line. The following two will give errors:
and
The compiler will react with a ’invalid character’ error when it encounters such constructs, regardless
of the -Mtp switch.
Remark: In TP and Delphi mode, nested comments are not allowed, for maximum compatibility with
existing code for those compilers.
13
CHAPTER 1. PASCAL TOKENS
1.3.3 Modifiers
The following is a list of all modifiers. They are not exactly reserved words in the sense that they can
be used as identifiers, but in specific places, they have a special meaning for the compiler, i.e., the
compiler considers them as part of the Pascal language.
Remark: Predefined types such as Byte, Boolean and constants such as maxint are not reserved words.
They are identifiers, declared in the system unit. This means that these types can be redefined in
other units. The programmer is however not encouraged to do this, as it will cause a lot of confusion.
Remark: As of version 2.5.1 it is possible to use reserved words as identifiers by escaping them with a & sign.
This means that the following is possible
var
&var : integer;
begin
&var:=1;
Writeln(&var);
end.
however, it is not recommended to use this feature in new code, as it makes code less readable. It
is mainly intended to fix old code when the list of reserved words changes and encompasses a word
that was not yet reserved (See also section 1.4, page 15).
14
CHAPTER 1. PASCAL TOKENS
1.4 Identifiers
Identifiers denote programmer defined names for specific constants, types, variables, procedures
and functions, units, and programs. All programmer defined names in the source code –excluding
reserved words– are designated as identifiers.
Identifiers consist of between 1 and 127 significant characters (letters, digits and the underscore
character), of which the first must be a letter (a-z or A-Z), or an underscore (_). The following
diagram gives the basic syntax for identifiers.
Identifiers
-
- identifier letter -
_ 6 letter
digit
_
Like Pascal reserved words, identifiers are case insensitive, that is, both
myprocedure;
and
MyProcedure;
program testdo;
procedure &do;
begin
end;
begin
&do;
end.
The reserved word do is used as an identifier for the declaration as well as the invocation of the
procedure ’do’.
Hint directives
15
CHAPTER 1. PASCAL TOKENS
-
- hint directive -
Deprecated
string constant
Experimental
Platform
Unimplemented
Whenever an identifier marked with a hint directive is later encountered by the compiler, then a
warning will be displayed, corresponding to the specified hint.
deprecated The use of this identifier is deprecated, use an alternative instead. The deprecated key-
word can be followed by a string constant with a message. The compiler will show this mes-
sage whenever the identifier is encountered.
experimental The use of this identifier is experimental: this can be used to flag new features that
should be used with caution.
platform This is a platform-dependent identifier: it may not be defined on all platforms.
unimplemented This should be used on functions and procedures only. It should be used to signal
that a particular feature has not yet been implemented.
Const
AConst = 12 deprecated;
var
p : integer platform;
begin
Something:=P+AConst;
end;
begin
Something;
end.
Hint directives can follow all kinds of identifiers: units, constants, types, variables, functions, proce-
dures and methods.
1.6 Numbers
Numbers are by default denoted in decimal notation. Real (or decimal) numbers are written using
engineering or scientific notation (e.g. 0.314E1).
For integer type constants, Free Pascal supports 4 formats:
16
CHAPTER 1. PASCAL TOKENS
3. As of version 1.0.7, Octal format (base 8) is also supported. To specify a constant in octal
format, prepend it with an ampersand (&). For instance 15 is specified in octal notation as
&17.
4. Binary notation (base 2). A binary number can be specified by preceding it with a percent sign
(%). Thus, 255 can be specified in binary notation as %11111111.
Numbers
-
- hex digit sequence hex digit -
6
-
- octal digit sequence octal digit -
6
-
- bin digit sequence 1 -
60
-
- digit sequence digit -
6
-
- unsigned integer digit sequence -
$ hex digit sequence
& octal digit sequence
% bin digit sequence
- sign +
- -
-
-
- unsigned real digit sequence -
. digit sequence scale factor
-
- scale factor E digit sequence -
e sign
-
- unsigned number unsigned real -
unsigned integer
-
- signed number unsigned number -
sign
Remark: Octal and Binary notation are not supported in TP or Delphi compatibility mode.
17
CHAPTER 1. PASCAL TOKENS
1.7 Labels
A label is a name for a location in the source code to which can be jumped to from another location
with a goto statement. A Label is a standard identifier or a digit sequence.
Label
-
- label digit sequence -
identifier
Remark: The -Sg or -Mtp switches must be specified before labels can be used. By default, Free Pascal
doesn’t support label and goto statements. The {$GOTO ON} directive can also be used to allow
use of labels and the goto statement.
The following are examples of valid labels:
Label
123,
abc;
Character strings
-
- character string quoted string -
6 control string
-
- quoted string ’ string character ’ -
6
-
- string character Any character except ’ or CR -
”
-
- control string # unsigned integer -
6
The string consists of standard, 8-bit ASCII characters or Unicode (normally UTF-8 encoded) char-
acters. The control string can be used to specify characters which cannot be typed on a
keyboard, such as #27 for the escape character.
The single quote character can be embedded in the string by typing it twice. The C construct of
escaping characters in the string (using a backslash) is not supported in Pascal.
The following are valid string constants:
18
CHAPTER 1. PASCAL TOKENS
or
19
Chapter 2
Constants
Just as in Turbo Pascal, Free Pascal supports both ordinary and typed constants. They are declared
in a constant declaration block in a unit, program or class, function or procedure declaration (section
16.5, page 229).
Constant declaration
-
- constant declaration identifier = expression hintdirectives ; -
6
The compiler must be able to evaluate the expression in a constant declaration at compile time. This
means that most of the functions in the Run-Time library cannot be used in a constant declaration.
Operators such as +, -, *, /, not, and, or, div, mod, ord, chr, sizeof, pi,
int, trunc, round, frac, odd can be used, however. For more information on expres-
sions, see chapter 12, page 155.
When a previously declared ordinary constant is used in the code, the compiler will insert the actual
value of the constant instead of the constant name. That is, the following 2 pieces of code are entirely
equivalent:
Const
One = 1;
begin
Writeln(One);
end.
The above will produce the same code as if one had written:
20
CHAPTER 2. CONSTANTS
begin
Writeln(1);
end.
• Ordinal types
• Set types
• Pointer types (but the only allowed value is Nil).
• Real types
• Char,
• String
Const
e = 2.7182818; { Real type constant. }
a = 2; { Ordinal (Integer) type constant. }
c = ’4’; { Character type constant. }
s = ’This is a constant string’; {String type constant.}
sc = chr(32)
ls = SizeOf(Longint);
P = Nil;
Ss = [1,2];
Assigning a value to an ordinary constant is not permitted. Thus, given the previous declaration, the
following will result in a compiler error:
For string constants, the type of the string is dependent on some compiler switches. If a specific type
is desired, a typed constant should be used, as explained in the following section.
Prior to version 1.9, Free Pascal did not correctly support 64-bit constants. As of version 1.9, 64-bit
constants can be specified.
21
CHAPTER 2. CONSTANTS
-
- typed constant constant -
address constant
array constant
record constant
procedural constant
Contrary to ordinary constants, a value can be assigned to them at run-time. This is an old concept
from Turbo Pascal, which has been replaced with support for initialized variables: For a detailed
description, see section 4.4, page 65.
Support for assigning values to typed constants is controlled by the {$J} directive: it can be switched
off, but is on by default (for Turbo Pascal compatibility). Initialized variables are always allowed.
Remark: It should be stressed that typed constants are automatically initialized at program start. This is also
true for local typed constants and initialized variables. Local typed constants are also initialized at
program start. If their value was changed during previous invocations of the function, they will retain
their changed value, i.e. they are not initialized each time the function is invoked.
Resourcestring
FileMenu = ’&File...’;
EditMenu = ’&Edit...’;
All string constants defined in the resourcestring section are stored in special tables. The strings in
these tables can be manipulated at runtime with some special mechanisms in the objpas unit.
Semantically, the strings act like ordinary constants; It is not allowed to assign values to them (except
through the special mechanisms in the objpas unit). However, they can be used in assignments or
expressions as ordinary string constants. The main use of the resourcestring section is to provide an
easy means of internationalization.
More on the subject of resourcestrings can be found in the Programmer’s Guide, and in the objpas
unit reference.
Remark: Note that a resource string which is given as an expression will not change if the parts of the expres-
sion are changed:
resourcestring
Part1 = ’First part of a long string.’;
Part2 = ’Second part of a long string.’;
Sentence = Part1+’ ’+Part2;
If the localization routines translate Part1 and Part2, the Sentence constant will not be trans-
lated automatically: it has a separate entry in the resource string tables, and must therefor be trans-
lated separately. The above construct simply says that the initial value of Sentence equals Part1+’
’+Part2.
22
CHAPTER 2. CONSTANTS
Remark: Likewise, when using resource strings in a constant array, only the initial values of the resource
strings will be used in the array: when the individual constants are translated, the elements in the
array will retain their original value.
resourcestring
Yes = ’Yes.’;
No = ’No.’;
Var
YesNo : Array[Boolean] of string = (No,Yes);
B : Boolean;
begin
Writeln(YesNo[B]);
end.
This will print ’Yes.’ or ’No.’ depending on the value of B, even if the constants Yes and No have
been localized by some localization mechanism.
23
Chapter 3
Types
All variables have a type. Free Pascal supports the same basic types as Turbo Pascal, with some extra
types from Delphi as well as some of its own.
The programmer can declare his own types, which is in essence defining an identifier that can be
used to denote this custom type when declaring variables further in the source code. Declaring a
type happens in a Type block (section 16.5, page 229), which is a collection of type declarations,
separated by semicolons:
Type declaration
-
- type declaration identifier = type ; -
hint directives
Types
-
- type simple type -
string type
structured type
pointer type
procedural type
generic type
specialized type
type alias
24
CHAPTER 3. TYPES
Simple types
-
- simple type ordinal type -
real type
-
- real type real type identifier -
1. Ordinal types are countable and ordered, i.e. it is, in principle, possible to start counting them
one by one, in a specified order. This property allows the operation of functions as Inc, Ord,
Dec on ordinal types to be defined.
2. Ordinal values have a smallest possible value. Trying to apply the Pred function on the
smallest possible value will generate a range check error if range checking is enabled.
3. Ordinal values have a largest possible value. Trying to apply the Succ function on the largest
possible value will generate a range check error if range checking is enabled.
Remark: Int64 and QWord are considered ordinal types on 64-bit CPUs. On 32-bit types they have some
of the characteristics of ordinals, but they cannot be used e.g. in for loops.
Integers
Name
Integer
Shortint
SmallInt
Longint
Longword
Int64
Byte
Word
Cardinal
QWord
Boolean
ByteBool
WordBool
LongBool
QWordBool
Char
25
CHAPTER 3. TYPES
The integer types, and their ranges and sizes, that are predefined in Free Pascal are listed in table
(3.2). Please note that the qword and int64 types are not true ordinals, so some Pascal constructs
will not work with these two integer types.
The integer type maps to the smallint type in the default Free Pascal mode. It maps to either a
longint in either Delphi or ObjFPC mode. The cardinal type is currently always mapped to the
longword type.
Remark: All decimal constants which do no fit within the -2147483648..2147483647 range are silently and
automatically parsed as 64-bit integer constants as of version 1.9.0. Earlier versions would convert it
to a real-typed constant.
Remark: In newer Delphi versions, the longint type is platform and CPU dependent. This is not so in FPC,
where longint is 32-bit on all platforms.
As a pascal compiler, Free Pascal does automatic type conversion and upgrading in expressions
where different kinds of integer types are used:
1. Every platform has a "native" integer size, depending on whether the platform is 8-bit, 16-bit,
32-bit or 64-bit. e.g. On AVR this is 8-bit.
2. Every integer smaller than the "native" size is promoted to a signed version of the "native" size.
Integers equal to the "native" size keep their signedness.
3. The result of binary arithmetic operators (+, -, *, etc.) is determined in the following way:
(a) If at least one of the operands is larger than the native integer size, the result is chosen
to be the smallest type that encompasses the ranges of the types of both operands. This
means that mixing an unsigned with a smaller or equal in size signed will produce a
signed type that is larger than both of them.
(b) If both operands have the same signedness, the result is the same type as them. The
only exception is subtracting (-): in the case of unsigned-unsigned subtracting produces
a signed result in FPC (as in Delphi, but not in TP7).
(c) Mixing signed and unsigned operands of the "native" int size produces a larger signed
result. This means that mixing longint and longword on 32-bit platforms will produce
an int64. Similarly, mixing byte and shortint on 8-bit platforms (AVR) will produce a
smallint.
26
CHAPTER 3. TYPES
Boolean types
Free Pascal supports the Boolean type, with its two pre-defined possible values True and False.
These are the only two values that can be assigned to a Boolean type. Of course, any expression
that resolves to a boolean value, can also be assigned to a boolean type.
In addition to the simple Boolean type, the additional Boolean8, Boolean16, Boolean32
and Boolean64 types exist. There are in fact integer types, which are assignment-compatible with
the simple boolean type. As an integer, the values for True and False are 1 and 0. This can be
used to interfac with C code that defines a boolean of this size with values 0 and 1.
To make interfacing with C even easier, Free Pascal also supports the ByteBool, WordBool,
LongBool and QWordBool types. These are of type Byte, Word, Longint or Int64, but are
again assignment compatible with a Boolean. The only difference with the Boolean8/16/32/64
types is in what values are considered true or false: The value False is equivalent to 0 (zero) and
any nonzero value is considered True when converting to a boolean value. A boolean value of
True is converted to Not(0) in case it is assigned to a variable of type ByteBool, WordBool,
LongBool or QWordBool.
Assuming B to be of type Boolean, the following are valid assignments:
B := True;
B := False;
B := 1<>2; { Results in B := True }
...
B := False;
A := B and Func;
27
CHAPTER 3. TYPES
Enumeration types
Enumeration types are supported in Free Pascal. On top of the Turbo Pascal implementation, Free
Pascal allows also a C-style extension of the enumeration type, where a value is assigned to a partic-
ular element of the enumeration list.
Enumerated types
-
- enumerated type ( identifier list ) -
6 assigned enum list
,
-
- identifier list identifier -
6 ,
-
- assigned enum list identifier := expression -
6 ,
(see chapter 12, page 155 for how to use expressions) When using assigned enumerated types, the
assigned elements must be in ascending numerical order in the list, or the compiler will complain.
The expressions used in assigned enumerated elements must be known at compile time. So the
following is a correct enumerated type declaration:
Type
Direction = ( North, East, South, West );
Type
EnumType = (one, two, three, forty := 40,fortyone);
As a result, the ordinal number of forty is 40, and not 3, as it would be when the ’:= 40’ wasn’t
present. The ordinal value of fortyone is then 41, and not 4, as it would be when the assignment
wasn’t present. After an assignment in an enumerated definition the compiler adds 1 to the assigned
value to assign to the next enumerated value.
When specifying such an enumeration type, it is important to keep in mind that the enumerated
elements should be kept in ascending order. The following will produce a compiler error:
Type
EnumType = (one, two, three, forty := 40, thirty := 30);
It is necessary to keep forty and thirty in the correct order. When using enumeration types it is
important to keep the following points in mind:
1. The Pred and Succ functions cannot be used on this kind of enumeration types. Trying to
do this anyhow will result in a compiler error.
2. Enumeration types are stored using a default, independent of the actual number of values:
the compiler does not try to optimize for space. This behaviour can be changed with the
{$PACKENUM n} compiler directive, which tells the compiler the minimal number of bytes
to be used for enumeration types. For instance
28
CHAPTER 3. TYPES
Type
{$PACKENUM 4}
LargeEnum = ( BigOne, BigTwo, BigThree );
{$PACKENUM 1}
SmallEnum = ( one, two, three );
Var S : SmallEnum;
L : LargeEnum;
begin
WriteLn (’Small enum : ’,SizeOf(S));
WriteLn (’Large enum : ’,SizeOf(L));
end.
Small enum : 1
Large enum : 4
More information can be found in the Programmer’s Guide, in the compiler directives section.
Subrange types
A subrange type is a range of values from an ordinal type (the host type). To define a subrange type,
one must specify its limiting values: the highest and lowest value of the type.
Subrange types
-
- subrange type constant .. constant -
Type
Longint = $80000000..$7fffffff;
Integer = -32768..32767;
shortint = -128..127;
byte = 0..255;
Word = 0..65535;
Type
Days = (monday,tuesday,wednesday,thursday,friday,
saturday,sunday);
WorkDays = monday .. friday;
WeekEnd = Saturday .. Sunday;
29
CHAPTER 3. TYPES
types are supported, and these depend on the target processor and emulation options. The true Turbo
Pascal compatible types are listed in table (3.4).
The Comp type is, in effect, a 64-bit integer and is not available on all target platforms. To get more
information on the supported types for each platform, refer to the Programmer’s Guide.
The currency type is a fixed-point real data type which is internally used as an 64-bit integer type
(automatically scaled with a factor 10000), this minimalizes rounding errors.
3.2.2 WideChar
Free Pascal supports the type WideChar. A WideChar is exactly 2 bytes in size, and contains one
UNICODE character in UTF-16 encoding.
A unicode character can be specified by its character value (an UTF-16 code), by preceding the
ordinal value with the number symbol (#).
A normal ansi (1-byte) character literal can also be used for a widechar, the compiler will automati-
cally convert it to a 2-byte UTF-16 character.
The following defines some greek characters (phi, omega):
30
CHAPTER 3. TYPES
Const
C3 : widechar = #$03A8;
C4 : widechar = #$03A9;
Const
C3 : widechar = widechar($03A8);
C4 : widechar = widechar($03A9);
String Type
-
- string type string -
[ unsigned integer ]
type string ( unsigned integer )
ansistring
If there is a size specifier (using square brackets), then its maximum value - indicating the maximum
size of the string - is 255. If there is a codepage specifier, (using round brackets) it indicates an
ansistring with associated code page information.
The meaning of a string declaration statement without size and code page indication is interpreted
differently depending on the {$H} switch:
var
A : String;
If no size and code page indication indication is present, the above declaration can declare an an-
sistring or a short string.
Whatever the actual type, single byte strings can be used interchangeably. The compiler always takes
care of the necessary type conversions. Note, however, that the result of an expression that contains
ansistrings and short strings will always be an ansistring.
1 As of version 3.0 of Free Pascal
31
CHAPTER 3. TYPES
Short strings
1. If the $H switch is off: {$H-}, the string declaration will always be a short string declaration.
2. If the switch is on {$H+}, and there is a maximum length (the size) specifier, the declaration
is a short string declaration.
Short strings are always assumed to use the system code page. The predefined type ShortString
is defined as a string of size 255:
ShortString = String[255];
If the size of the string is not specified, 255 is taken as a default. The actual length of the string can
be obtained with the Length standard runtime routine. For example in
{$H-}
Type
NameString = String[10];
StreetString = String;
For short strings, the length is stored in the character at index 0. Old Turbo Pascal code relies on this,
and it is implemented similarly in Free Pascal.
Despite this, to write portable code, it is best to set the length of a shortstring with the SetLength
call, and to retrieve it with the Length call. These functions will always work, whatever the internal
representation of the shortstrings or other strings in use: this allows easy switching between the
various string types.
Ansistrings
Ansistrings are strings that have no length limit, and have a code page associated with them2 . They
are reference counted and are guaranteed to be null terminated.
Internally, an ansistring is treated as a pointer: the actual content of the string is stored on the heap,
as much memory as needed to store the string content is allocated.
If no codepage is given in the declaration, the system codepage is assumed. What codepage this is,
is determined by the DefaultSystemCodePage constant in the system unit.
This is all handled transparently, i.e. they can be manipulated as a normal short string. Ansistrings
can be defined using the predefined AnsiString type or using the string keyword in mode
{$H+}.
2 codepage was introduced in version 3.0 of Free Pascal
32
CHAPTER 3. TYPES
Remark: The null-termination does not mean that null characters (char(0) or #0) cannot be used: the null-
termination is not used internally, but is there for convenience when dealing with external routines
that expect a null-terminated string (as most C routines do).
If the {$H} switch is on, then a string definition using the regular String keyword that doesn’t
contain a length specifier, will be regarded as an ansistring as well. If a length specifier is present, a
short string will be used, regardless of the {$H} setting.
If the string is empty (’’), then the internal pointer representation of the string pointer is Nil. If the
string is not empty, then the pointer points to a structure in heap memory.
The internal representation as a pointer, and the automatic null-termination make it possible to type-
cast an ansistring to a pchar. If the string is empty (so the pointer is Nil) then the compiler makes
sure that the typecasted pchar will point to a null byte.
Assigning one ansistring to another doesn’t involve moving the actual string. A statement
S2:=S1;
results in the reference count of S2 being decreased with 1, The reference count of S1 is increased
by 1, and finally S1 (as a pointer) is copied to S2. This is a significant speed-up in the code.
If the reference count of a string reaches zero, then the memory occupied by the string is deallocated
automatically, and the pointer is set to Nil, so no memory leaks arise.
When an ansistring is declared, the Free Pascal compiler initially allocates just memory for a pointer,
not more. This pointer is guaranteed to be Nil, meaning that the string is initially empty. This is true
for local and global ansistrings or ansistrings that are part of a structure (arrays, records or objects).
Remark: Note that a function result in this regard is considered equivalent to a var parameter and hence will
not be initialized to Nil. As a consequence it may point to a legitimate non-Nil ansistring when
the function begins.
This does introduce an overhead. For instance, declaring
Var
A : Array[1..100000] of string;
Will copy the value Nil 100,000 times into A. When A goes out of scope, then the reference count
of the 100,000 strings will be decreased by 1 for each of these strings. All this happens invisible to
the programmer, but when considering performance issues, this is important.
Memory for the string content will be allocated only when the string is assigned a value. If the string
goes out of scope, then its reference count is automatically decreased by 1. If the reference count
reaches zero, the memory reserved for the string is released.
If a value is assigned to a character of a string that has a reference count greater than 1, such as in the
following statements:
then a copy of the string is created before the assignment. This is known as copy-on-write semantics.
It is possible to force a string to have reference count equal to 1 with the UniqueString call:
S:=T;
R:=T; // Reference count of T is at least 3
UniqueString(T);
// Reference count of T is guaranteed 1
It’s recommended to do this e.g. when typecasting an ansistring to a PChar var and passing it to a C
routine that modifies the string.
33
CHAPTER 3. TYPES
The Length function must be used to get the length of an ansistring: the length is not stored at
character 0 of the ansistring. The construct
L:=ord(S[0]);
which was valid for Turbo Pascal shortstrings, is no longer correct for Ansistrings. The compiler will
warn if such a construct is encountered.
To set the length of an ansistring, the SetLength function must be used. Constant ansistrings have
a reference count of -1 and are treated specially, The same remark as for Length must be given:
The construct
L:=12;
S[0]:=Char(L);
which was valid for Turbo Pascal shortstrings, is no longer correct for Ansistrings. The compiler will
warn if such a construct is encountered.
Ansistrings are converted to short strings by the compiler if needed, this means that the use of an-
sistrings and short strings can be mixed without problems.
Ansistrings can be typecasted to PChar or Pointer types:
Var P : Pointer;
PC : PChar;
S : AnsiString;
begin
S :=’This is an ansistring’;
PC:=Pchar(S);
P :=Pointer(S);
There is a difference between the two typecasts. When an empty ansistring is typecasted to a pointer,
the pointer will be Nil. If an empty ansistring is typecasted to a PChar, then the result will be a
pointer to a zero byte (an empty string).
The result of such a typecast must be used with care. In general, it is best to consider the result of
such a typecast as read-only, i.e. only suitable for passing to a procedure that needs a constant pchar
argument.
It is therefore not advisable to typecast one of the following:
1. Expressions.
2. Strings that have reference count larger than 1. In this case you should call Uniquestring
to ensure the string has reference count 1.
Since strings have code page information associated with them, it is important to know which code
page a string uses:
34
CHAPTER 3. TYPES
• The RawBytestring type has no code page information associated with it.
• Constant strings have the code page of the source file. If none is specified the system codepage
is used (CP_ACP).
See Programmer’s Guide, {$CODEPAGE } directive.
These rules mean that it is perfectly possible for an AnsiString variable to get a code page that
differs from its declared code page. E.g. in the third case SOURCE_CP could be CP_ACP, while
after the assignment it may have a dynamic code page equal to DefaultSystemCodePage.
Note: as mentioned above, whether or not a potential code page conversion happens only depends on
the declared code pages of the involved strings. This means that if you assign one AnsiString(X) to
another AnsiString(X) and the former’s dynamic code was different from X, the string data will not
be converted to code page X by the assignment.
All this means that in the following code:
Type
TString1 = Type String(1252);
TString2 = Type String(1251);
Var
A : TString1;
B : TString2;
begin
A:=’123’+’345’+intToStr(123);
B:=A;
Writeln(’B : ’,StringRefCount(B));
Writeln(’A : ’,StringRefCount(A));
end.
35
CHAPTER 3. TYPES
The compiler will convert the contents in string B to the codepage of string A. Note that if a code page
conversion takes place, the reference count mechanism is not used: a new string will be allocated.
This automated conversion of code pages can slow down the code seriously, so care must be taken to
see to it that the code page conversions are limited to a minimum.
The code page of a string can be set explicitly using the SetCodePage routine of the system unit.
Calling this routine will convert the value of a string to the requested code page.
Remark: Code page conversions can result in loss of data: if a certain character cannot be represented in the
target code page, the output for that character is undefined.
Remark: When a string whose static code page equals the source file code page, to anything with code page
CP_ACP (i.e., a plain ansistring, shortstring, or pchar), no conversion will be performed either. No
code page conversion is done when s can result in loss of data: if a certain character cannot be
represented in the target code page, the output for that character is undefined.
Remark: Code page support requires quite some helper routines, these are implemented in the unicodestring
manager. On windows, the system routines are used for this. On Unices, the cwstring unit
can be used to link to the C library and use the C library conversion support. Alternatively, the
fpwidestring unit contains a unicodestring manager implemented natively in Object Pascal.
RawByteString
The pre-defined RawByteString type is an ansistring string type without codepage information
(CP_NONE):
Type
RawByteString = type ansistring(CP_NONE);
It is treated specially in the sense that if the conversion routines encounter CP_NONE in a source or
target string, no code page conversion is performed, the code page of the source string is preserved.
For this reason, most single-byte string routines in the system and sysutils units use the RawByteString
type.
UTF8String
Single-byte code page strings can only store the characters available in that code page. Characters
that are not present in the code page, cannot be represented by that string. The UTF-8 unicode
encoding is an encoding that can be used with single-byte strings: The ASCII characters (ordinal
value <128) in this encoding map exactly to the CP_ACP encoding. This fact is used to define a
single byte string type that can contain all characters:
Type
UTF8String = type AnsiString(CP_UTF8);
The UTF8string string type can be used to represent all Unicode characters. This power comes as
a price, though. Since a unicode character may require several bytes to be represented in the UTF-8
encoding, there are 2 points to take care of when using UTF8String:
1. The character index – which retrieves a byte-sized char at a certain position – must be used
with care: the expression S[i] will not necessarily be a valid character for a string S of type
UTF8String.
2. The byte length of the string is not equal to the number of characters in the string. The standard
function length cannot be used to get the character length, it will always return the byte
length.
36
CHAPTER 3. TYPES
For all other code pages, the number of characters in a single-byte code page string is equal to the
byte length of the string.
UnicodeStrings
Unicodestrings (used to represent unicode character strings) are implemented in much the same way
as ansistrings: reference counted, null-terminated arrays, only they are implemented as arrays of
WideChars instead of regular Chars. A WideChar is a two-byte character (an element of a
DBCS: Double Byte Character Set). Mostly the same rules apply for UnicodeStrings as for
AnsiStrings. The compiler transparently converts UnicodeStrings to AnsiStrings and vice versa.
Const
ws2: unicodestring = ’phi omega : ’#$03A8’ ’#$03A9;
WideStrings
The Widestring type (used to represent unicode character strings in COM applications) is imple-
mented in much the same way as Unicodestring on Windows, and on other platforms, they are
simply the same type. If interaction with COM is not required, the UnicodeString type should
be used.
On Windows, unlike UnicodeString, the WideString type is not reference counted, and are
allocated with a special windows function which allows them to be used for OLE automation. This
means they are implemented as null-terminated arrays of WideChars instead of regular Chars.
WideString obeys the same rules as for UnicodeStrings. Similar to unicodestrings, the com-
piler transparenty converts WideStrings to AnsiStrings and vice versa.
For typecasting and conversion, the same rules apply as for the UnicodeString type.
S := ’This is a string.’;
S := ’One’+’, Two’+’, Three’;
S := ’This isn’’t difficult !’;
S := ’This is a weird character : ’#145’ !’;
37
CHAPTER 3. TYPES
As can be seen, the single quote character is represented by 2 single-quote characters next to each
other. Strange characters can be specified by their character value (usually an ASCII code). The
example shows also that two strings can be added. The resulting string is just the concatenation
of the first with the second string, without spaces in between them. Strings can not be subtracted,
however.
Whether the constant string is stored as an ansistring or a short string depends on the settings of the
{$H} switch.
program one;
var P : PChar;
begin
P := ’This is a null-terminated string.’;
WriteLn (P);
end.
program two;
const P : PChar = ’This is a null-terminated string.’;
begin
WriteLn (P);
end.
These examples also show that it is possible to write the contents of the string to a file of type
Text. The strings unit contains procedures and functions that manipulate the PChar type as in the
standard C library. Since it is equivalent to a pointer to a type Char variable, it is also possible to do
the following:
Program three;
Var S : String[30];
P : PChar;
begin
S := ’This is a null-terminated string.’#0;
P := @S[1];
WriteLn (P);
end.
This will have the same result as the previous two examples. Null-terminated strings cannot be added
as normal Pascal strings. If two PChar strings must be concatenated; the functions from the unit
strings must be used.
However, it is possible to do some pointer arithmetic. The operators + and - can be used to do
operations on PChar pointers. In table (3.5), P and Q are of type PChar, and I is of type Longint.
38
CHAPTER 3. TYPES
Operation Result
P + I Adds I to the address pointed to by P.
I + P Adds I to the address pointed to by P.
P - I Substracts I from the address pointed to by P.
P - Q Returns, as an integer, the distance between 2 addresses
(or the number of characters between P and Q)
Structured Types
-
- structured type array type -
record type
object type
class type
class reference type
interface type
set type
file type
39
CHAPTER 3. TYPES
Unlike Delphi, Free Pascal does not support the keyword Packed for all structured types. In the
following sections each of the possible structured types is discussed. It will be mentioned when a
type supports the packed keyword.
When a structured type is declared, no assumptions should be made about the internal position of the
elements in the type. The compiler will lay out the elements of the structure in memory as it thinks
will be most suitable. That is, the order of the elements will be kept, but the location of the elements
are not guaranteed, and is partially governed by the $PACKRECORDS directive (this directive is
explained in the Programmer’s Guide).
However, Free Pascal allows controlling the layout with the Packed and Bitpacked keywords.
The meaning of these words depends on the context:
Bitpacked In this case, the compiler will attempt to align ordinal types on bit boundaries, as ex-
plained below.
Packed The meaning of the Packed keyword depends on the situation:
Packing on byte boundaries means that each new element of a structured type starts on a byte
boundary.
The byte packing mechanism is simple: the compiler aligns each element of the structure on the first
available byte boundary, even if the size of the previous element (small enumerated types, subrange
types) is less than a byte.
When using the bit packing mechanism, the compiler calculates for each ordinal type how many bits
are needed to store it. The next ordinal type is then stored on the next free bit. Non-ordinal types
- which include but are not limited to - sets, floats, strings, (bitpacked) records, (bitpacked) arrays,
pointers, classes, objects, and procedural variables, are stored on the first available byte boundary.
Note that the internals of the bitpacking are opaque: they can change at any time in the future. What
is more: the internal packing depends on the endianness of the platform for which the compilation is
done, and no conversion between platforms are possible. This makes bitpacked structures unsuitable
for storing on disk or transport over networks. The format is however the same as the one used by
the GNU Pascal Compiler, and the Free Pascal team aims to retain this compatibility in the future.
There are some more restrictions to elements of bitpacked structures:
• The address cannot be retrieved, unless the bit size is a multiple of 8 and the element happens
to be stored on a byte boundary.
• An element of a bitpacked structure cannot be used as a var parameter, unless the bit size is a
multiple of 8 and the element happens to be stored on a byte boundary.
To determine the size of an element in a bitpacked structure, there is the BitSizeOf function. It
returns the size - in bits - of the element. For other types or elements of structures which are not
40
CHAPTER 3. TYPES
bitpacked, this will simply return the size in bytes multiplied by 8, i.e., the return value is then the
same as 8*SizeOf.
The size of bitpacked records and arrays is limited:
The reason is that the offset of an element must be calculated with the maximum integer size of the
system.
3.3.1 Arrays
Free Pascal supports arrays as in Turbo Pascal. Multi-dimensional arrays and (bit)packed arrays are
also supported, as well as the dynamic arrays of Delphi:
Array types
-
- array type array of type -
packed [ ordinal type ]
bitpacked 6 ,
Static arrays
When the range of the array is included in the array definition, it is called a static array. Trying to
access an element with an index that is outside the declared range will generate a run-time error (if
range checking is on). The following is an example of a valid array declaration:
Type
RealArray = Array [1..100] of Real;
Valid indexes for accessing an element of the array are between 1 and 100, where the borders 1 and
100 are included. As in Turbo Pascal, if the array component type is in itself an array, it is possible
to combine the two arrays into one multi-dimensional array. The following declaration:
Type
APoints = array[1..100] of Array[1..3] of Real;
Type
APoints = array[1..100,1..3] of Real;
The functions High and Low return the high and low bounds of the leftmost index type of the array.
In the above case, this would be 100 and 1. You should use them whenever possible, since it improves
maintainability of your code. The use of both functions is just as efficient as using constants, because
they are evaluated at compile time.
When static array-type variables are assigned to each other, the contents of the whole array is copied.
This is also true for multi-dimensional arrays:
41
CHAPTER 3. TYPES
program testarray1;
Type
TA = Array[0..9,0..9] of Integer;
var
A,B : TA;
I,J : Integer;
begin
For I:=0 to 9 do
For J:=0 to 9 do
A[I,J]:=I*J;
For I:=0 to 9 do
begin
For J:=0 to 9 do
Write(A[I,J]:2,’ ’);
Writeln;
end;
B:=A;
Writeln;
For I:=0 to 9 do
For J:=0 to 9 do
A[9-I,9-J]:=I*J;
For I:=0 to 9 do
begin
For J:=0 to 9 do
Write(B[I,J]:2,’ ’);
Writeln;
end;
end.
Dynamic arrays
As of version 1.1, Free Pascal also knows dynamic arrays: In that case the array range is omitted, as
in the following example:
Type
TByteArray = Array of Byte;
When declaring a variable of a dynamic array type, the initial length of the array is zero. The actual
length of the array must be set with the standard SetLength function, which will allocate the
necessary memory to contain the array elements on the heap. The following example will set the
length to 1000:
Var
A : TByteArray;
begin
SetLength(A,1000);
After a call to SetLength, valid array indexes are 0 to 999: the array index is always zero-based.
42
CHAPTER 3. TYPES
Note that the length of the array is set in elements, not in bytes of allocated memory (although these
may be the same). The amount of memory allocated is the size of the array multiplied by the size
of 1 element in the array. The memory will be disposed of at the exit of the current procedure or
function.
It is also possible to resize the array: in that case, as much of the elements in the array as will fit in
the new size, will be kept. The array can be resized to zero, which effectively resets the variable.
At all times, trying to access an element of the array with an index that is not in the current length of
the array will generate a run-time error.
Dynamic arrays are reference counted: assignment of one dynamic array-type variable to another
will let both variables point to the same array. Contrary to ansistrings, an assignment to an element
of one array will be reflected in the other: there is no copy-on-write. Consider the following example:
Var
A,B : TByteArray;
begin
SetLength(A,10);
A[0]:=33;
B:=A;
A[0]:=31;
After the second assignment, the first element in B will also contain 31.
It can also be seen from the output of the following example:
program testarray1;
Type
TA = Array of array of Integer;
var
A,B : TA;
I,J : Integer;
begin
Setlength(A,10,10);
For I:=0 to 9 do
For J:=0 to 9 do
A[I,J]:=I*J;
For I:=0 to 9 do
begin
For J:=0 to 9 do
Write(A[I,J]:2,’ ’);
Writeln;
end;
B:=A;
Writeln;
For I:=0 to 9 do
For J:=0 to 9 do
A[9-I,9-J]:=I*J;
For I:=0 to 9 do
begin
For J:=0 to 9 do
Write(B[I,J]:2,’ ’);
Writeln;
43
CHAPTER 3. TYPES
end;
end.
The output of this program will be a matrix of numbers, and then the same matrix, mirrored.
As remarked earlier, dynamic arrays are reference counted: if in one of the previous examples A goes
out of scope and B does not, then the array is not yet disposed of: the reference count of A (and B) is
decreased with 1. As soon as the reference count reaches zero the memory, allocated for the contents
of the array, is disposed of.
The SetLength call will make sure the reference count of the returned array is 1, that is, if 2 dy-
namic array variables were pointing to the same memory they will no longer do so after the setlength
call:
program testunique;
Type
TA = array of Integer;
var
A,B : TA;
I : Integer;
begin
Setlength(A,10);
For I:=0 to 9 do
A[I]:=I;
B:=A;
SetLength(B,6);
A[0]:=123;
For I:=0 to 5 do
Writeln(B[I]);
end.
It is also possible to copy and/or resize the array with the standard Copy function, which acts as the
copy function for strings:
program testarray3;
Type
TA = array of Integer;
var
A,B : TA;
I : Integer;
begin
Setlength(A,10);
For I:=0 to 9 do
A[I]:=I;
B:=Copy(A,3,6);
For I:=0 to 5 do
Writeln(B[I]);
end.
The Copy function will copy 6 elements of the array to a new array. Starting at the element at index
44
CHAPTER 3. TYPES
Object Pascal is a strictly typed language. 2 technically distinct types are sometimes considered
assignment compatible (i.e. a value of one type can be assigned to a variable of another type) under
certain circumstances. Dynamic arrays are considered assignment compatible when they use the
same element type. That means that the following will compile:
{$mode objfpc}
Type
TA = Array of Integer;
TB = Array of Integer;
Var
A : TA;
B : TB;
begin
SetLength(A,1);
A[0]:=1;
B:=A;
end.
But the following will not, even though the integer and word types are assignement compatible:
{$mode objfpc}
Type
TA = Array of Word;
TB = Array of Integer;
Var
A : TA;
B : TB;
begin
SetLength(A,1);
A[0]:=1;
B:=A;
end.
As of version 3.0 of Free Pascal, Dynamic array types have a constructor. This is intrinsic, the
compiler provides it. Up to version 2.6.4, the only way to initialize a dynamic array was as follows:
Type
TIntegerArray = Array of Integer;
45
CHAPTER 3. TYPES
var
A : TIntegerArray;
begin
SetLength(A,3);
A[0]:=1;
A[1]:=2;
A[3]:=3;
Writeln(Length(A));
end.
As of version 3.0 of Free Pascal, an dynamic array can be initialized using a constructor-like syntax.
The constructor is called Create, and accepts as parameters a variable number of parameters of the
element type of the array type. This means the above initialization can now be done as:
Type
TIntegerArray = Array of Integer;
var
A : TIntegerArray;
begin
A:=TIntegerArray.Create(1,2,3);
Writeln(Length(A));
end.
Note that this will not work for dynamic arrays for which no type was created. That is, the following
will not work:
var
A : Array of Integer;
begin
A:=Array of Integer.Create(1,2,3);
Writeln(Length(A));
end.
Type
TIntegerArray = Array of Integer;
TIntegerArrayArray = Array of TIntegerArray;
var
A : TIntegerArrayArray;
begin
A:=TIntegerArrayArray.Create(TIntegerArray.Create(1,2,3),
TIntegerArray.Create(4,5,6),
TIntegerArray.Create(7,8,9));
Writeln(’Length ’,length(A));
end.
46
CHAPTER 3. TYPES
However, since it is a constructor (code is run at run-time) it is not possible to use this in an initialized
variable syntax. That is, the following will not work:
Type
TIntegerArray = Array of Integer;
var
A : TIntegerArray = TIntegerArray.Create(1,2,3);
begin
Writeln(’Length ’,length(A));
end.
Arrays can be packed and bitpacked. 2 array types which have the same index type and element type,
but which are differently packed are not assignment compatible.
However, it is possible to convert a normal array to a bitpacked array with the pack routine. The
reverse operation is possible as well; a bitpacked array can be converted to a normally packed array
using the unpack routine, as in the following example:
Var
foo : array [ ’a’..’f’ ] of Boolean
= ( false, false, true, false, false, false );
bar : bitpacked array [ 42..47 ] of Boolean;
baz : array [ ’0’..’5’ ] of Boolean;
begin
pack(foo,’a’,bar);
unpack(bar,baz,’0’);
end.
More information about the pack and unpack routines can be found in the system unit reference.
Record types
-
- record type record end -
packed field list
bitpacked
-
- field list fixed fields -
variant part ;
fixed fields ;
-
- fixed fields identifier list : type -
6 ;
47
CHAPTER 3. TYPES
-
- variant part case ordinal type of variant -
identifier : 6 ;
-
- variant constant : ( ) -
6 , field list
Type
Point = Record
X,Y,Z : Real;
end;
RPoint = Record
Case Boolean of
False : (X,Y,Z : Real);
True : (R,theta,phi : Real);
end;
BetterRPoint = Record
Case UsePolar : Boolean of
False : (X,Y,Z : Real);
True : (R,theta,phi : Real);
end;
The variant part must be last in the record. The optional identifier in the case statement serves to
access the tag field value, which otherwise would be invisible to the programmer. It can be used to
see which variant is active at a certain time3 . In effect, it introduces a new field in the record.
Remark: It is possible to nest variant parts, as in:
Type
MyRec = Record
X : Longint;
Case byte of
2 : (Y : Longint;
case byte of
3 : (Z : Longint);
);
end;
48
CHAPTER 3. TYPES
The layout and size of variant parts in records is determined by replacing them with a field whose
type is a record with as first element a field of the tag field type if an identifier was declared for this
tag field, followed by the elements of the biggest variant.
Field F2’s offset in a record is equal to the sum of the previous field F1’s offset and F1’s size, rounded
up to a multiple of F2’s required alignment. This required alignment is calculated as follows:
• The required alignment is set to the default alignment of the field’s type, possibly adjusted
based on the fact that this type occurs in a record and on the field’s location in the record.
• If the required alignment is smaller than the currently active {$CODEALIGN RECORDMIN=X}
setting, it is changed to this X value.
• If the currently active {$ALIGN N} or {$PACKRECORDS N} setting is
The size of a record is equal to the sum of the record’s last field’s offset and this field’s size, rounded
up to a multiple of the record’s required alignment. The record’s required alignment is calculated as
follows:
• The required alignment is set to the alignment of the record’s field with the largest alignment,
as determined while laying out the record.
• If the current {$ALIGN N} or {$PACKRECORDS N} setting is different from C and the
required alignment is larger than than the currently active {$CODEALIGN RECORDMAX=X},
the required alignment is changed to X.
Free Pascal also supports a ’packed record’, which is a record where all the elements are byte-aligned.
As a result, the two following declarations are equivalent:
{$PackRecords 1}
Trec2 = Record
A : Byte;
B : Word;
end;
{$PackRecords default}
and
49
CHAPTER 3. TYPES
Note the {$PackRecords Default} after the first declaration to restore the default setting!
Given the platform-dependent nature of how records are laid out in memory, the only way to ensure a
compatible layout across platforms (assuming that all fields are declared using a type with the same
meaning across these same platforms) is by using {$PACKRECORDS 1}.
In particular, if a typed file with records, produced by a Turbo Pascal program, must be read, then
chances are that attempting to read that file correctly will fail. The reason is that Free Pascal’s default
{$PACKRECORDS N} setting is not necessarily compatible with Turbo Pascal’s. It can be changed
to {$PACKRECORDS 1} or {$PACKRECORDS 2} depending on the setting used in the Turbo
Pascal program that create the file (although it may still fail with {$PACKRECORDS 2} due to
different type alignment requirements between 16 bit MSDOS and your current platform).
The same remark goes for Delphi: exchanging data is only guaranteed to be possible if both the
producer and consumer use a packed record, or if they are on the same platform and use the same
{$PACKRECORDS X} setting.
Set Types
-
- set type set of ordinal type -
Each of the elements of SetType must be of type TargetType. TargetType can be any ordinal
type with a range between 0 and 255. A set can contain at most 255 elements. The following are
valid set declaration:
Type
Junk = Set of Char;
Days = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
Var
WorkDays : Set of days;
The compiler stores small sets (less than 32 elements) in a Longint, if the type range allows it. This
allows for faster processing and decreases program size. Otherwise, sets are stored in 32 bytes.
Several operations can be done on sets: taking unions or differences, adding or removing elements,
comparisons. These are documented in section 12.8.5, page 165
50
CHAPTER 3. TYPES
File types
-
- file type file -
of type
If no type identifier is given, then the file is an untyped file; it can be considered as equivalent to a file
of bytes. Untyped files require special commands to act on them (see Blockread, Blockwrite).
The following declaration declares a file of records:
Type
Point = Record
X,Y,Z : real;
end;
PointFile = File of Point;
Internally, files are represented by the FileRec record, which is declared in the Dos or SysUtils
units.
A special file type is the Text file type, represented by the TextRec record. A file of type Text
uses special input-output routines. The default Input, Output and StdErr file types are defined
in the system unit: they are all of type Text, and are opened by the system unit initialization code.
3.4 Pointers
Free Pascal supports the use of pointers. A variable of the pointer type contains an address in memory,
where the data of another variable may be stored. A pointer type can be defined as follows:
Pointer types
-
- pointer type ˆ type identifier -
As can be seen from this diagram, pointers are typed, which means that they point to a particular
kind of data. The type of this data must be known at compile time.
Dereferencing the pointer (denoted by adding ˆ after the variable name) behaves then like a variable.
This variable has the type declared in the pointer declaration, and the variable is stored in the address
that is pointed to by the pointer variable. Consider the following example:
Program pointers;
type
51
CHAPTER 3. TYPES
Buffer = String[255];
BufPtr = ^Buffer;
Var B : Buffer;
BP : BufPtr;
PP : Pointer;
etc..
In this example, BP is a pointer to a Buffer type; while B is a variable of type Buffer. B takes
256 bytes memory, and BP only takes 4 (or 8) bytes of memory: enough memory to store an address.
The expression
BP^
BP^[23]
Var p : ^Longint;
The difference is that the former declaration allocates memory for the pointer only (not for the array),
and the second declaration allocates memory for the entire array. If the former is used, the memory
must be allocated manually, using the Getmem function. The reference Pˆ is then the same as p[0].
The following program illustrates this maybe more clear:
program PointerArray;
var i : Longint;
p : ^Longint;
pp : array[0..100] of Longint;
begin
for i := 0 to 100 do pp[i] := i; { Fill array }
p := @pp[0]; { Let p point to pp }
for i := 0 to 100 do
if p[i]<>pp[i] then
WriteLn (’Ohoh, problem !’)
end.
Free Pascal supports pointer arithmetic as C does. This means that, if P is a typed pointer, the
instructions
Inc(P);
Dec(P);
will increase, respectively decrease the address the pointer points to with the size of the type P is a
pointer to. For example
52
CHAPTER 3. TYPES
Var P : ^Longint;
...
Inc (p);
will increase P with 4, because 4 is the size of a longint. If the pointer is untyped, a size of 1 byte is
assumed (i.e. as if the pointer were a pointer to a byte: ˆbyte.)
Normal arithmetic operators on pointers can also be used, that is, the following are valid pointer
arithmetic operations:
Here, the value that is added or subtracted is multiplied by the size of the type the pointer points to.
In the previous example P1 will be decremented by 16 bytes, and P2 will be incremented by 16.
Type
TListItem = Record
Data : Integer;
Next : ^TListItem;
end;
When trying to compile this, the compiler will complain that the TListItem type is not yet defined
when it encounters the Next declaration: This is correct, as the definition is still being parsed.
To be able to have the Next element as a typed pointer, a ’Forward type declaration’ must be intro-
duced:
Type
PListItem = ^TListItem;
TListItem = Record
Data : Integer;
Next : PTListItem;
end;
When the compiler encounters a typed pointer declaration where the referenced type is not yet known,
it postpones resolving the reference till later. The pointer definition is a ’Forward type declaration’.
The referenced type should be introduced later in the same Type block. No other block may come
between the definition of the pointer type and the referenced type. Indeed, even the word Type
53
CHAPTER 3. TYPES
itself may not re-appear: in effect it would start a new type-block, causing the compiler to resolve all
pending declarations in the current block.
In most cases, the definition of the referenced type will follow immediately after the definition of
the pointer type, as shown in the above listing. The forward defined type can be used in any type
definition following its declaration.
Note that a forward type declaration is only possible with pointer types and classes, not with other
types.
Procedural types
- procedural type
- function header -
procedure header of object ; call modifiers
is nested
-
- function header function formal parameter list : result type -
-
- procedure header procedure formal parameter list -
-
- call modifiers register -
cdecl
pascal
stdcall
safecall
inline
For a description of formal parameter lists, see chapter 14, page 189. The two following examples
are valid type declarations:
54
CHAPTER 3. TYPES
From this example, the difference with Turbo Pascal is clear: In Turbo Pascal it isn’t necessary to
use the address operator (@) when assigning a procedural type variable, whereas in Free Pascal it is
required. In case the -MDelphi or -MTP switches are used, the address operator can be dropped.
Remark: The modifiers concerning the calling conventions must be the same as the declaration; i.e. the
following code would give an error:
Because the TOneArgCcall type is a procedure that uses the cdecl calling convention.
In case the is nested modified is added, then the procedural variable can be used with nested pro-
cedures. This requires that the sources be compiled in macpas or ISO mode, or that the nestedprocvars
modeswitch be activated:
{$modeswitch nestedprocvars}
program tmaclocalprocparam3;
type
tnestedprocvar = procedure is nested;
var
tempp: tnestedprocvar;
procedure n;
55
CHAPTER 3. TYPES
begin
writeln( ’calling through n’)
end;
procedure q;
procedure r;
begin
if qi = 1 then
writeln( ’success for r’)
else
begin
writeln( ’fail’);
halt( 1)
end
end;
begin
qi:= 1;
p1( @r);
p2( @r);
p1( @n);
p2( @n);
end;
begin
q;
end.
In case one wishes to assign methods of a class to a variable of procedural type, the procedural type
must be declared with the of object modifier.
The two following examples are valid type declarations for method procedural variables (also known
as event handlers because of their use in GUI design):
A method of the correct signature can be assigned to these functions. When called, Self will be
pointing to the instance of the object that was used to assign the method procedure.
The following object methods can be assigned to oproc and ofunc:
Type
TMyObject = Class(TObject)
Procedure DoX (Var X : integer);
Function DoY: Real;
end;
Var
56
CHAPTER 3. TYPES
M : TMyObject;
begin
oproc:[email protected];
ofunc:[email protected];
end;
Type
TSomeMethod = Procedure of object;
TMyObject = Class(TObject)
Procedure DoSomething;
end;
Procedure TMyObject.DoSomething;
begin
Writeln(’In DoSomething’);
end;
var
X,Y : TMyObject;
P1,P2 : TSomeMethod;
begin
X:=TMyObject.Create;
Y:=TMyObject.Create;
P1:[email protected];
P2:[email protected];
Writeln(’Same method : ’,P1=P2);
end.
If both pointers must be compared, a typecast to TMethod must be done, and both pointers should be
compared.
57
CHAPTER 3. TYPES
Structured types such as sets, records, arrays, files, objects and classes are not assignment-compatible
with a variant, as well as pointers. Interfaces and COM or CORBA objects can be assigned to a
variant (basically because they are simply a pointer).
This means that the following assignments are valid:
Type
TMyEnum = (One,Two,Three);
Var
V : Variant;
I : Integer;
B : Byte;
W : Word;
Q : Int64;
E : Extended;
D : Double;
En : TMyEnum;
AS : AnsiString;
WS : WideString;
begin
V:=I;
V:=B;
V:=W;
V:=Q;
V:=E;
V:=En;
V:=D;
V:=AS;
V:=WS;
end;
Program testv;
uses variants;
Var
A : Variant;
I : integer;
begin
A:=VarArrayCreate([1,10],varInteger);
For I:=1 to 10 do
A[I]:=I;
end.
58
CHAPTER 3. TYPES
program testv3;
uses Variants;
Var
V : Variant;
I : Integer;
begin
V:=’100’;
I:=V;
Writeln(’I : ’,I);
V:=’Something else’;
I:=V;
Writeln(’I : ’,I);
end.
The first assignment will work, but the second will not, as Something else cannot be converted
to a valid integer value. An EConvertError exception will be the result.
The result of an expression involving a variant will be of type variant again, but this can be assigned
to a variable of a different type - if the result can be converted to a variable of this type.
Note that expressions involving variants take more time to be evaluated, and should therefore be used
with caution. If a lot of calculations need to be made, it is best to avoid the use of variants.
When considering implicit type conversions (e.g. byte to integer, integer to double, char to string)
the compiler will ignore variants unless a variant appears explicitly in the expression.
Var
W : Variant;
V : String;
begin
W:=CreateOleObject(’Word.Application’);
V:=W.Application.Version;
59
CHAPTER 3. TYPES
The line
V:=W.Application.Version;
is executed by inserting the necessary code to query the dispatch interface stored in the variant W, and
execute the call if the needed dispatch information is found.
Type aliases
-
- type alias identifier -
type
Type
MyInteger = Integer;
This creates a new name to refer to the Integer type, but does not create an actual new type. That
is, 2 variables:
Var
A : MyInteger;
B : Integer;
Will actually have the same type from the point of view of the compiler (namely: Integer).
The above presents a way to make types platform independent, by only using the alias types, and then
defining these types for each platform individually. Any programmer who then uses these custom
types doesn’t have to worry about the underlying type size: it is opaque to him. It also allows to use
shortcut names for fully qualified type names. e.g. define system.longint as Olongint and
then redefine longint.
The alias is frequently seen to re-expose a type:
Unit A;
Interface
Uses B;
Type
MyType = B.MyType;
60
CHAPTER 3. TYPES
This construction is often seen after some refactoring, when moving some declarations from unit A
to unit B, to preserve backwards compatibility of the interface of unit A.
The second case is slightly more subtle:
Type
MyInteger = Type Integer;
This not only creates a new name to refer to the Integer type, but actually creates a new type. That
is, 2 variables:
Var
A : MyInteger;
B : Integer;
Will not have the same type from the point of view of the compiler. However, these 2 types will be
assignment compatible. That means that an assignment
A:=B;
will work.
The difference can be seen when examining type information:
If TypeInfo(MyInteger)<>TypeInfo(Integer) then
Writeln(’MyInteger and Integer are different types’);
The compiler function TypeInfo returns a pointer to the type information in the binary. Since the 2
types MyInteger and Integer are different, they will generate different type information blocks,
and the pointers will differ.
There are 3 consequences of having different types:
1. That they have different typeinfo, hence different RTTI (Run-Time Type Information).
2. They can be used in function overloads, that is
will work. This will not work with a simple type alias.
3. They can be used in operator overloads, that is
61
CHAPTER 3. TYPES
62
Chapter 4
Variables
4.1 Definition
Variables are explicitly named memory locations with a certain type. When assigning values to
variables, the Free Pascal compiler generates machine code to move the value to the memory location
reserved for this variable. Where this variable is stored depends on where it is declared:
• Global variables are variables declared in a unit or program, but not inside a procedure or func-
tion. They are stored in fixed memory locations, and are available during the whole execution
time of the program.
• Local variables are declared inside a procedure or function. Their value is stored on the pro-
gram stack, i.e. not at fixed locations.
The Free Pascal compiler handles the allocation of these memory locations transparently, although
this location can be influenced in the declaration.
The Free Pascal compiler also handles reading values from or writing values to the variables trans-
parently. But even this can be explicitly handled by the programmer when using properties.
Variables must be explicitly declared when they are needed. No memory is allocated unless a variable
is declared. Using a variable identifier (for instance, a loop variable) which is not declared first, is an
error which will be reported by the compiler.
4.2 Declaration
The variables must be declared in a variable declaration block of a unit or a procedure or function
(section 16.5, page 229). It looks as follows:
Variable declaration
-
- variable declaration identifier : type -
= expression
- hint directive ; -
variable modifiers
63
CHAPTER 4. VARIABLES
- variable modifiers
- absolute integer expression -
6 identifier
; export
; cvar
; external
string constant name string constant
hint directive
- -
Var
curterm1 : integer;
curterm11 : integer = 1 ;
1. The first form (curterm1) defines a regular variable. The compiler manages everything by
itself.
2. The second form (curterm2) declares also a regular variable, but specifies that the assembler
name for this variable equals the name of the variable as written in the source.
3. The third form (curterm3) declares a variable which is located externally: the compiler will
assume memory is located elsewhere, and that the assembler name of this location is specified
by the name of the variable, as written in the source. The name may not be specified.
4. The fourth form is completely equivalent to the third, it declares a variable which is stored
externally, and explicitly gives the assembler name of the location. If cvar is not used, the
name must be specified.
5. The fifth form is a variant of the fourth form, only the name of the library in which the memory
is reserved is specified as well.
6. The sixth form declares a variable (curterm6), and tells the compiler that it is stored in the
same location as another variable (curterm1).
7. The seventh form declares a variable (curterm7), and tells the compiler that the assembler
label of this variable should be the name of the variable (case sensitive) and must be made
public. i.e. it can be referenced from other object files.
64
CHAPTER 4. VARIABLES
8. The eighth form (curterm8) is equivalent to the seventh: ’public’ is an alias for ’export’.
9. The ninth and tenth form are equivalent: they specify the assembler name of the variable.
10. the elevents form declares a variable (curterm11) and initializes it with a value (1 in the
above case).
Note that assembler names must be unique. It’s not possible to declare or export 2 variables with the
same assembler name.
4.3 Scope
Variables, just as any identifier, obey the general rules of scope. In addition, initialized variables are
initialized when they enter scope:
• Global initialized variables are initialized once, when the program starts.
• Local initialized variables are initialized each time the procedure is entered.
Note that the behaviour for local initialized variables is different from the one of a local typed con-
stant. A local typed constant behaves like a global initialized variable.
Var
S : String = ’This is an initialized string’;
The value of the variable following will be initialized with the provided value. The following is an
even better way of doing this:
Const
SDefault = ’This is an initialized string’;
Var
S : String = SDefault;
Initialization is often used to initialize arrays and records. For arrays, the initialized elements must
be specified, surrounded by round brackets, and separated by commas. The number of initialized
elements must be exactly the same as the number of elements in the declaration of the type. As an
example:
Var
tt : array [1..3] of string[20] = (’ikke’, ’gij’, ’hij’);
ti : array [1..3] of Longint = (1,2,3);
65
CHAPTER 4. VARIABLES
For constant records, each element of the record should be specified, in the form Field: Value,
separated by semicolons, and surrounded by round brackets. As an example:
Type
Point = record
X,Y : Real
end;
Var
Origin : Point = (X:0.0; Y:0.0);
The order of the fields in a constant record needs to be the same as in the type declaration, otherwise
a compile-time error will occur.
Remark: It should be stressed that initialized variables are initialized when they come into scope, in difference
with typed constants, which are initialized at program start. This is also true for local initialized
variables. Local initialized variables are initialized whenever the routine is called. Any changes that
occurred in the previous invocation of the routine will be undone, because they are again initialized.
Remark: Care should be taken when using initialized pointer types such as PChars. In the following exam-
ples, S is a pointer, pointing to a block of constant (read-only) program data. Assigning S
procedure foo1;
var
s: PChar = ’PChar’;
begin
s[0] := ’a’;
end;
procedure foo2;
var
s: PChar;
begin
s := ’PChar’;
s[0] := ’a’;
end;
type
TRecord = record
i: LongInt;
s: AnsiString;
66
CHAPTER 4. VARIABLES
end;
var
i: LongInt;
o: TObject;
r: TRecord;
begin
i := Default(LongInt); // 0
o := Default(TObject); // Nil
r := Default(TRecord); // ( i: 0; s: ’’)
end.
type
TRecord = record
i: LongInt;
s: AnsiString;
end;
var
i: ^LongInt;
o: ^TObject;
r: ^TRecord;
begin
i:=GetMem(SizeOf(Longint));
i^ := Default(LongInt); // 0
o:=GetMem(SizeOf(TObject));
o^ := Default(TObject); // Nil
r:=GetMem(SizeOf(TRecord));
r^ := Default(TRecord); // ( i: 0; s: ’’)
end.
It works for all types, except the various file types (or complex types containing a file type).
Remark:
• For generics, the use of Default is especially useful, since the type of a variable may not be
known during the declaration of a generic. For more information section 8.7, page 125.
• Function results are available as a Result identifier, and as such resemble variables. They
are not variables, but are treated as passed-by-reference parameters. They are therefor not
initialized.
Threadvar
IOResult : Integer;
67
CHAPTER 4. VARIABLES
If no threads are used, the variable behaves as an ordinary variable. If threads are used then a copy is
made for each thread (including the main thread). Note that the copy is made with the original value
of the variable, not with the value of the variable at the time the thread is started.
Threadvars should be used sparingly: There is an overhead for retrieving or setting the variable’s
value. If possible at all, consider using local variables; they are always faster than thread variables.
Threads are not enabled by default. For more information about programming threads, see the chapter
on threads in the Programmer’s Guide.
4.7 Properties
A global block can declare properties, just as they could be defined in a class. The difference is that
the global property does not need a class instance: there is only 1 instance of this property. Other
than that, a global property behaves like a class property. The read/write specifiers for the global
property must also be regular procedures, not methods.
The concept of a global property is specific to Free Pascal, and does not exist in Delphi. ObjFPC
mode is required to work with properties.
The concept of a global property can be used to ’hide’ the location of the value, or to calculate the
value on the fly, or to check the values which are written to the property.
The declaration is as follows:
Properties
-
- property definition identifier property specifiers -
property interface
-
- property interface : type identifier -
property parameter list
- -
index integerconstant
-
- property parameter list [ parameter declaration ] -
6 ;
- property specifiers
- -
read specifier write specifier default specifier
-
- read specifier read field or function -
-
- write specifier write field or procedure -
-
- default specifier default -
constant
nodefault
-
- field or procedure field identifier -
procedure identifier
-
- field or function field identifier -
function identifier
68
CHAPTER 4. VARIABLES
{$mode objfpc}
unit testprop;
Interface
Property
MyProp : Integer Read GetMyInt Write SetMyInt;
Implementation
Uses sysutils;
Var
FMyInt : Integer;
begin
Result:=FMyInt;
end;
begin
If ((Value mod 2)=1) then
Raise Exception.Create(’MyProp can only contain even value’);
FMyInt:=Value;
end;
end.
The read/write specifiers can be hidden by declaring them in another unit which must be in the uses
clause of the unit. This can be used to hide the read/write access specifiers for programmers, just as
if they were in a private section of a class (discussed below). For the previous example, this could
look as follows:
{$mode objfpc}
unit testrw;
Interface
Implementation
Uses sysutils;
Var
FMyInt : Integer;
69
CHAPTER 4. VARIABLES
begin
Result:=FMyInt;
end;
begin
If ((Value mod 2)=1) then
Raise Exception.Create(’Only even values are allowed’);
FMyInt:=Value;
end;
end.
{$mode objfpc}
unit testprop;
Interface
uses testrw;
Property
MyProp : Integer Read GetMyInt Write SetMyInt;
Implementation
end.
70
Chapter 5
Objects
5.1 Declaration
Free Pascal supports object oriented programming. In fact, most of the compiler is written using
objects. Here we present some technical questions regarding object oriented programming in Free
Pascal.
Objects should be treated as a special kind of record. The record contains all the fields that are
declared in the objects definition, and pointers to the methods that are associated to the objects’ type.
An object is declared just as a record would be declared; except that now, procedures and functions
can be declared as if they were part of the record. Objects can ”inherit” fields and methods from
”parent” objects. This means that these fields and methods can be used as if they were included in
the objects declared as a ”child” object.
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared as
public, protected or private. By default, fields and methods are public, and are exported
outside the current unit.
Fields or methods that are declared private are only accessible in the current unit: their scope is
limited to the implementation of the current unit.
The prototype declaration of an object is as follows:
object types
-
- object component list end -
packed heritage 6
-
- heritage ( object type identifier ) -
-
- component list -
object visibility specifier const definition
6
- -
field definition method definition
6 6
-
- field definition identifier list : type ; -
var static;
class
71
CHAPTER 5. OBJECTS
-
- const definition const identifier = constant expression ; -
-
- object visibility specifier private -
protected
public
As can be seen, as many private and public blocks as needed can be declared.
The following is a valid definition of an object:
Type
TObj = object
Private
Caption : ShortString;
Public
Constructor init;
Destructor done;
Procedure SetCaption (AValue : String);
Function GetCaption : String;
end;
It contains a constructor/destructor pair, and a method to get and set a caption. The Caption field
is private to the object: it cannot be accessed outside the unit in which TObj is declared.
Remark: In MacPas mode, the Object keyword is replaced by the class keyword for compatibility with
other pascal compilers available on the Mac. That means that objects cannot be used in MacPas
mode.
Remark: Free Pascal also supports the packed object. This is the same as an object, only the elements (fields)
of the object are byte-aligned, just as in the packed record. The declaration of a packed object is
similar to the declaration of a packed record :
Type
TObj = packed object
Constructor init;
...
end;
Pobj = ^TObj;
Var PP : Pobj;
5.2 Fields
Object Fields are like record fields. They are accessed in the same way as a record field would be
accessed : by using a qualified identifier. Given the following declaration:
72
CHAPTER 5. OBJECTS
AnObject.AField := 0;
Procedure TAnObject.AMethod;
begin
...
AField := 0;
...
end;
Or, one can use the self identifier. The self identifier refers to the current instance of the object:
Procedure TAnObject.AMethod;
begin
...
Self.AField := 0;
...
end;
One cannot access fields that are in a private or protected sections of an object from outside the ob-
jects’ methods. If this is attempted anyway, the compiler will complain about an unknown identifier.
It is also possible to use the with statement with an object instance, just as with a record:
With AnObject do
begin
Afield := 12;
AMethod;
end;
In this example, between the begin and end, it is as if AnObject was prepended to the Afield
and Amethod identifiers. More about this in section 13.2.8, page 186.
{$mode delphi}
{$static on}
type
cl=object
l : longint; static;
class var v : integer;
end;
var
73
CHAPTER 5. OBJECTS
cl1,cl2 : cl;
begin
Writeln(’Static’);
cl1.l:=2;
writeln(cl2.l);
cl2.l:=3;
writeln(cl1.l);
Writeln(cl.l);
Writeln(’Class’);
cl1.v:=4;
writeln(cl2.v);
cl2.v:=5;
writeln(cl1.v);
Writeln(cl.v);
end.
Static
2
3
3
Class
4
5
5
Note that the last line of code references the object type itself (cl), and not an instance of the object
(cl1 or cl2).
-
- constructor declaration constructor header ; subroutine block -
-
- destructor declaration destructor header ; subroutine block -
-
- constructor header constructor identifier -
qualified method identifier
- formal parameter list -
-
- destructor header destructor identifier -
qualified method identifier
- formal parameter list -
74
CHAPTER 5. OBJECTS
A constructor/destructor pair is required if the object uses virtual methods. The reason is that for an
object with virtual methods, some internal housekeeping must be done: this housekeeping is done by
the constructor1 .
In the declaration of the object type, a simple identifier should be used for the name of the constructor
or destructor. When the constructor or destructor is implemented, a qualified method identifier should
be used, i.e. an identifier of the form objectidentifier.methodidentifier.
Free Pascal supports also the extended syntax of the New and Dispose procedures. In case a
dynamic variable of an object type must be allocated the constructor’s name can be specified in the
call to New. The New is implemented as a function which returns a pointer to the instantiated object.
Consider the following declarations:
Type
TObj = object;
Constructor init;
...
end;
Pobj = ^TObj;
Var PP : Pobj;
pp := new (Pobj,Init);
and
new(pp,init);
and also
new (pp);
pp^.init;
In the last case, the compiler will issue a warning that the extended syntax of new and dispose
must be used to generate instances of an object. It is possible to ignore this warning, but it’s better
programming practice to use the extended syntax to create instances of an object. Similarly, the
Dispose procedure accepts the name of a destructor. The destructor will then be called, before
removing the object from the heap.
In view of the compiler warning remark, the following chapter presents the Delphi approach to
object-oriented programming, and may be considered a more natural way of object-oriented pro-
gramming.
5.5 Methods
Object methods are just like ordinary procedures or functions, only they have an implicit extra pa-
rameter : self. Self points to the object with which the method was invoked. When implementing
methods, the fully qualified identifier must be given in the function header. When declaring methods,
a normal identifier must be given.
1A pointer to the VMT must be set up.
75
CHAPTER 5. OBJECTS
5.5.1 Declaration
The declaration of a method is much like a normal function or procedure declaration, with some ad-
ditional specifiers, as can be seen from the following diagram, which is part of the object declaration:
methods
-
- method definition class function header ; method directives -
procedure header
constructor header
destructor header
-
- method directives -
virtual ; call modifiers ;
abstract ;
from the point of view of declarations, Method definitions are normal function or procedure
declarations. Contrary to TP and Delphi, fields can be declared after methods in the same block, i.e.
the following will generate an error when compiling with Delphi or Turbo Pascal, but not with FPC:
Type
MyObj = Object
Field : Longint;
Procedure Doit;
end;
Normal (static) methods are methods that have been declared without a abstract or virtual
keyword. When calling a static method, the declared (i.e. compile time) method of the object is
used. For example, consider the following declarations:
Type
TParent = Object
...
procedure Doit;
...
end;
PParent = ^TParent;
TChild = Object(TParent)
...
procedure Doit;
...
end;
PChild = ^TChild;
76
CHAPTER 5. OBJECTS
As it is visible, both the parent and child objects have a method called Doit. Consider now the
following declarations and calls:
Var
ParentA,ParentB : PParent;
Child : PChild;
begin
ParentA := New(PParent,Init);
ParentB := New(PChild,Init);
Child := New(PChild,Init);
ParentA^.Doit;
ParentB^.Doit;
Child^.Doit;
Of the three invocations of Doit, only the last one will call TChild.Doit, the other two calls will
call TParent.Doit. This is because for static methods, the compiler determines at compile time
which method should be called. Since ParentB is of type TParent, the compiler decides that
it must be called with TParent.Doit, even though it will be created as a TChild. There may
be times when the method that is actually called should depend on the actual type of the object at
run-time. If so, the method cannot be a static method, but must be a virtual method.
Virtual methods
To remedy the situation in the previous section, virtual methods are created. This is simply done
by appending the method declaration with the virtual modifier. The descendent object can then
override the method with a new implementation by re-declaring the method (with the same parameter
list) using the virtual keyword.
Going back to the previous example, consider the following alternative declaration:
Type
TParent = Object
...
procedure Doit;virtual;
...
end;
PParent = ^TParent;
TChild = Object(TParent)
...
procedure Doit;virtual;
...
end;
PChild = ^TChild;
As it is visible, both the parent and child objects have a method called Doit. Consider now the
following declarations and calls :
Var
ParentA,ParentB : PParent;
Child : PChild;
begin
ParentA := New(PParent,Init);
77
CHAPTER 5. OBJECTS
ParentB := New(PChild,Init);
Child := New(PChild,Init);
ParentA^.Doit;
ParentB^.Doit;
Child^.Doit;
Now, different methods will be called, depending on the actual run-time type of the object. For
ParentA, nothing changes, since it is created as a TParent instance. For Child, the situation
also doesn’t change: it is again created as an instance of TChild.
For ParentB however, the situation does change: Even though it was declared as a TParent, it is
created as an instance of TChild. Now, when the program runs, before calling Doit, the program
checks what the actual type of ParentB is, and only then decides which method must be called.
Seeing that ParentB is of type TChild, TChild.Doit will be called. The code for this run-time
checking of the actual type of an object is inserted by the compiler at compile time.
The TChild.Doit is said to override the TParent.Doit. It is possible to acces the TParent.Doit
from within the varTChild.Doit, with the inherited keyword:
Procedure TChild.Doit;
begin
inherited Doit;
...
end;
In the above example, when TChild.Doit is called, the first thing it does is call TParent.Doit.
The inherited keyword cannot be used in static methods, only on virtual methods.
To be able to do this, the compiler keeps - per object type - a table with virtual methods: the VMT
(Virtual Method Table). This is simply a table with pointers to each of the virtual methods: each
virtual method has its fixed location in this table (an index). The compiler uses this table to look
up the actual method that must be used. When a descendent object overrides a method, the entry
of the parent method is overwritten in the VMT. More information about the VMT can be found in
Programmer’s Guide.
As remarked earlier, objects that have a VMT must be initialized with a constructor: the object
variable must be initialized with a pointer to the VMT of the actual type that it was created with.
Abstract methods
An abstract method is a special kind of virtual method. A method that is declared abstract does
not have an implementation for this method. It is up to inherited objects to override and implement
this method.
From this it follows that a method can not be abstract if it is not virtual (this can be seen from the
syntax diagram). A second consequence is that an instance of an object that has an abstract method
cannot be created directly.
The reason is obvious: there is no method where the compiler could jump to ! A method that is
declared abstract does not have an implementation for this method. It is up to inherited objects
to override and implement this method. Continuing our example, take a look at this:
Type
TParent = Object
...
procedure Doit;virtual;abstract;
...
78
CHAPTER 5. OBJECTS
end;
PParent=^TParent;
TChild = Object(TParent)
...
procedure Doit;virtual;
...
end;
PChild = ^TChild;
As it is visible, both the parent and child objects have a method called Doit. Consider now the
following declarations and calls :
Var
ParentA,ParentB : PParent;
Child : PChild;
begin
ParentA := New(PParent,Init);
ParentB := New(PChild,Init);
Child := New(PChild,Init);
ParentA^.Doit;
ParentB^.Doit;
Child^.Doit;
First of all, Line 3 will generate a compiler error, stating that one cannot generate instances of objects
with abstract methods: The compiler has detected that PParent points to an object which has an
abstract method. Commenting line 3 would allow compilation of the program.
Remark: If an abstract method is overridden, the parent method cannot be called with inherited, since
there is no parent method; The compiler will detect this, and complain about it, like this:
If, through some mechanism, an abstract method is called at run-time, then a run-time error will
occur. (run-time error 211, to be precise)
Class methods or methods declared with the static directive are methods that are global to the
object type. When called, the implicit ’self’ pointer is not available. This means that normal methods
cannot be called, and none of the fields of an object can be accessed. Class variables can be used,
however.
Class or static methods are regular methods, they can be assigned to a procedural variable.
The following program demonstrates all this. The commented-out statements will not compile.
{$APPTYPE CONSOLE}
{$IFDEF FPC}{$MODE DELPHI}{$H+}{$ENDIF}
type
TTest = object
const Epsylon = 100;
var f : integer;
class var cv1,cv2:integer;
procedure myproc;
79
CHAPTER 5. OBJECTS
procedure TTest.myproc;
begin
cv1:=0;
f:=1;
end;
procedure TTest.Testproc3;
begin
cv1:=3;
// f:=1;
end;
Var
P : Procedure;
begin
P:[email protected];
P:[email protected];
P:[email protected];
P:[email protected];
end.
Uncommenting one of the commented statements and trying to compile the resulting code will result
in a compiler error:
5.6 Visibility
For objects, 3 visibility specifiers exist : private, protected and public. If a visibility speci-
fier is not specified, public is assumed. Both methods and fields can be hidden from a programmer
by putting them in a private section. The exact visibility rule is as follows:
Private All fields and methods that are in a private block, can only be accessed in the module
80
CHAPTER 5. OBJECTS
(i.e. unit or program) that contains the object definition. They can be accessed from inside the
object’s methods or from outside them e.g. from other objects’ methods, or global functions.
Protected Is the same as Private, except that the members of a Protected section are also
accessible to descendent types, even if they are implemented in other modules.
Public fields and methods are always accessible, from everywhere. Fields and methods in a public
section behave as though they were part of an ordinary record type.
81
Chapter 6
Classes
In the Delphi approach to Object Oriented Programming, everything revolves around the concept
of ’Classes’. A class can be seen as a pointer to an object, or a pointer to a record, with methods
associated with it.
The difference between objects and classes is mainly that an object is allocated on the stack, as
an ordinary record would be, and that classes are always allocated on the heap. In the following
example:
Var
A : TSomeObject; // an Object
B : TSomeClass; // a Class
The main difference is that the variable A will take up as much space on the stack as the size of the
object (TSomeObject). The variable B, on the other hand, will always take just the size of a pointer
on the stack. The actual class data is on the heap.
From this, a second difference follows: a class must always be initialized through its constructor,
whereas for an object, this is not necessary. Calling the constructor allocates the necessary memory
on the heap for the class instance data.
Remark: In earlier versions of Free Pascal it was necessary, in order to use classes, to put the objpas unit in the
uses clause of a unit or program. This is no longer needed as of version 0.99.12. As of this version,
the unit will be loaded automatically when the -MObjfpc or -MDelphi options are specified, or
their corresponding directives are used:
{$mode objfpc}
{$mode delphi}
In fact, the compiler will give a warning if it encounters the objpas unit in a uses clause.
Class types
-
- class type class forward definition -
class definition
82
CHAPTER 6. CLASSES
-
- class forward definition class -
-
- class definition class -
packed heritage component list end
6
-
- heritage ( class type identifier ) -
implemented interfaces
-
- implemented interfaces , interface identifier -
6
-
- component list -
visibility specifier field definition
6
- -
const declaration part
6 type declaration part
variable declaration part
class variable declaration part
method definition
property definition
-
- class variable declaration part class variable declaration part -
-
- field definition identifier list : type ; -
static;
-
- method definition function header ;-
class procedure header
constructor header
desctuctor header
- -
virtual ; call modifiers ;
dynamic ; abstract
override
message integer constant
string constant
-
- class visibility specifier private -
strict protected
public
published
Remark: In MacPas mode, the Object keyword is replaced by the class keyword for compatibility with
other pascal compilers available on the Mac. That means that in MacPas mode, the reserved word
’class’ in the above diagram may be replaced by the reserved word ’object’.
In a class declaration, as many private, protected, published and public blocks as
needed can be used: the various blocks can be repeated, and there is no special order in which
they must appear.
Methods are normal function or procedure declarations. As can be seen, the declaration of a class is
almost identical to the declaration of an object. The real difference between objects and classes is in
the way they are created (see further in this chapter).
The visibility of the different sections is as follows:
83
CHAPTER 6. CLASSES
Private All fields and methods that are in a private block, can only be accessed in the module
(i.e. unit) that contains the class definition. They can be accessed from inside the classes’
methods or from outside them (e.g. from other classes’ methods)
Strict Private All fields and methods that are in a strict private block, can only be accessed
from methods of the class itself. Other classes or descendent classes (even in the same unit)
cannot access strict private members.
Protected Is the same as Private, except that the members of a Protected section are also
accessible to descendent types, even if they are implemented in other modules.
Strict Protected Is the same as Protected, except that the members of a Protected section
are also accessible to other classes implemented in the same unit. Strict protected
members are only visible to descendent classes, not to other classes in the same unit.
Public sections are always accessible.
Published From a language perspective, this is the same as a Public section, but the compiler
generates also type information that is needed for automatic streaming of these classes if the
compiler is in the {$M+} state. Fields defined in a published section must be of class type.
Array properties cannot be in a published section.
In the syntax diagram, it can be seen that a class can list implemented interfaces. This feature will be
discussed in the next chapter.
Classes can contain Class methods: these are functions that do not require an instance. The Self
identifier is valid in such methods, but refers to the class pointer (the VMT).
Remark: Like with functions and pointer types, sometimes a forward definition of a class is needed. A class
forward definition is simply the name of the class, with the keyword Class, as in the following
example:
Type
TClassB = Class;
TClassA = Class
B : TClassB;
end;
TClassB = Class
A : TClassA;
end;
When using a class forward definition, the class must be defined in the same unit, in the same section
(interface/implementation). It must not necessarily be defined in the same type section.
It is also possible to define class reference types:
-
- class of classtype -
Class reference types are used to create instances of a certain class, which is not yet known at compile
time, but which is specified at run time. Essentially, a variable of a class reference type contains a
pointer to the definition of the speficied class. This can be used to construct an instance of the class
corresponding to the definition, or to check inheritance. The following example shows how it works:
84
CHAPTER 6. CLASSES
Type
TComponentClass = Class of TComponent;
begin
// ...
Result:=AClass.Create(AOwner);
// ...
end;
This function can be passed a class reference of any class that descends from TComponent. The
following is a valid call:
Var
C : TComponent;
begin
C:=CreateComponent(TEdit,Form1);
end;
On return of the CreateComponent function, C will contain an instance of the class TEdit. Note
that the following call will fail to compile:
Var
C : TComponent;
begin
C:=CreateComponent(TStream,Form1);
end;
because TStream does not descend from TComponent, and AClass refers to a TComponent
class. The compiler can (and will) check this at compile time, and will produce an error.
References to classes can also be used to check inheritance:
begin
If not (Instance is TMinClass)
or ((Instance is TMaxClass)
and (Instance.ClassType<>TMaxClass)) then
Raise Exception.Create(SomeError)
end;
The above example will raise an exception if the passed instance is not a descendent of TMinClass
or a descendent of TMaxClass.
More about instantiating a class can be found in section 6.3, page 87.
85
CHAPTER 6. CLASSES
{$mode objfpc}
type
cl=class
l : longint;
end;
var
cl1,cl2 : cl;
begin
cl1:=cl.create;
cl2:=cl.create;
cl1.l:=2;
writeln(cl1.l);
writeln(cl2.l);
end.
2
0
The example demonstrates that values of fields are initialized with zero (or the equivalent of zero for
non ordinal types: empty string, empty array and so on).
The second way to declare a field (only available in more recent versions of Free Pascal) is using a
var block:
{$mode objfpc}
type
cl=class
var
l : longint;
end;
86
CHAPTER 6. CLASSES
be referenced from within the classes’ methods, but can also be referenced from outside the class by
providing the fully qualified name.
Again, there are 2 ways to define class variables. The first one is equivalent to the way it is done in
objects, using a static modifier:
For instance, the output of the following program is the same as the output for the version using an
object:
{$mode objfpc}
type
cl=class
l : longint;static;
end;
var
cl1,cl2 : cl;
begin
cl1:=cl.create;
cl2:=cl.create;
cl1.l:=2;
writeln(cl2.l);
cl2.l:=3;
writeln(cl1.l);
Writeln(cl.l);
end.
2
3
3
Note that the last line of code references the class type itself (cl), and not an instance of the class
(cl1 or cl2).
In addition to the static field approach, in classes, a Class Var can be used. Similar to the way a
field can be defined in a variable block, a class variable can be declared in a class var block:
{$mode objfpc}
type
cl=class
class var
l : longint;
end;
87
CHAPTER 6. CLASSES
ClassVar := ClassType.ConstructorName;
The extended syntax of new and dispose can not be used to instantiate and destroy class instances:
That construct is reserved for use with objects only. Calling the constructor will provoke a call to
the virtual class method NewInstance, which, in its default implementation, calls GetMem, to
allocate enough space to hold the class instance data, and then zeroes out the memory.
After that, the constructor’s code is executed. The constructor has a pointer to its data, in Self.
Remark:
• The {$PackRecords } directive also affects classes, i.e. the alignment in memory of the
different fields depends on the value of the {$PackRecords } directive.
• Just as for objects and records, a packed class can be declared. This has the same effect as on
an object, or record, namely that the elements are aligned on 1-byte boundaries, i.e. as close
as possible.
• SizeOf(class) will return the same as SizeOf(Pointer), since a class is a pointer
to an object. To get the size of the class instance data, use the TObject.InstanceSize
method.
• If an exception happens during an the execution of a constructor, the destructor will be called
automatically.
Var
A : TComponent;
begin
A:=TComponent.Create;
A.Name:=’MyComponent’;
A.Free;
Writeln(’A is still assigned: ’,Assigned(A));
end.
After the call to Free, the variable A will not be Nil, the output of this program will be:
To make sure that the variable A is cleared after the destructor was called, the function FreeAndNil
from the SysUtils unit can be used. It will call Free and will then write Nil in the object pointer
(A in the above example):
88
CHAPTER 6. CLASSES
Var
A : TComponent;
begin
A:=TComponent.Create;
A.Name:=’MyComponent’;
FreeAndNil(A);
Writeln(’A is still assigned: ’,Assigned(A));
end.
After the call to FreeAndNil, the variable A will contain Nil, the output of this program will be:
Remark: if an exception happens during an the execution of a constructor, the destructor will be called auto-
matically.
6.5 Methods
6.5.1 Declaration
Declaration of methods in classes follows the same rules as method declarations in objects:
methods
-
- method definition function header ; method directives -
procedure header
constructor header
destructor header
-
- method directives -
virtual call modifiers ;
dynamic ; abstract
reintroduce ;
override ;
message constant expression
The only differences are the override, reintroduce and message directives.
6.5.2 Invocation
Method invocation for classes is no different than for objects. The following is a valid method
invocation:
89
CHAPTER 6. CLASSES
Type
ObjParent = Class
Procedure MyProc; virtual;
end;
ObjChild = Class(ObjPArent)
Procedure MyProc; virtual;
end;
The compiler will compile it, but using Inherited can produce strange effects.
The correct declaration is as follows:
Type
ObjParent = Class
Procedure MyProc; virtual;
end;
ObjChild = Class(ObjPArent)
Procedure MyProc; override;
end;
Type
ObjParent = Class
Procedure MyProc; virtual;
end;
ObjChild = Class(ObjPArent)
Procedure MyProc; reintroduce;
end;
90
CHAPTER 6. CLASSES
Class methods are methods that do not have an instance (i.e. Self does not point to a class instance)
but which follow the scoping and inheritance rules of a class. They can be used to return information
about the current class, for instance for registration or use in a class factory. Since no instance is
available, no information available in instances can be used.
Class methods can be called from inside a regular method, but can also be called using a class
identifier:
Var
AClass : TClass; // AClass is of type "type of class"
begin
..
if CompareText(AClass.ClassName,’TCOMPONENT’)=0 then
...
Var
MyClass : TObject;
begin
..
if MyClass.ClassNameis(’TCOMPONENT’) then
...
The reverse is not possible: Inside a class method, the Self identifier points to the VMT table of
the class. No fields, properties or regular methods are available inside a class method. Accessing a
regular property or method will result in a compiler error.
Note that class methods can be virtual, and can be overridden.
Class methods can be used as read or write specifiers for a regular property, but naturally, this property
will have the same value for all instances of the class, since there is no instance available in the class
method.
• There may be only one constructor per class. The name is arbitraty, but it can not have param-
eters.
• There may be only one destructor per class. The name is arbitrary, but it can not have parame-
ters.
91
CHAPTER 6. CLASSES
{$mode objfpc}
{$h+}
Type
TA = Class(TObject)
Private
Function GetA : Integer;
Procedure SetA(AValue : integer);
public
Class Constructor create;
Class Destructor destroy;
Property A : Integer Read GetA Write SetA;
end;
begin
Result:=-1;
end;
begin
//
end;
begin
Writeln(’Class constructor TA’);
end;
begin
Writeln(’Class destructor TA’);
end;
Var
A : TA;
92
CHAPTER 6. CLASSES
begin
end.
Class constructor TA
Class destructor TA
• They do not have a Self parameter. As a result, they cannot access properties or fields or
regular methods.
• They cannot be virtual.
• They can be assigned to regular procedural variables.
Their use is mainly to include the method in the namespace of the class as opposed to having the
procedure in the namespace of the unit. Note that they do have access to all class variables, types etc,
meaning something like this is possible:
{$mode objfpc}
{$h+}
Type
TA = Class(TObject)
Private
class var myprivatea : integer;
public
class Function GetA : Integer; static;
class Procedure SetA(AValue : Integer); static;
end;
begin
Result:=myprivateA;
end;
begin
myprivateA:=AValue;
end;
begin
TA.SetA(123);
Writeln(TA.MyPrivateA);
end.
93
CHAPTER 6. CLASSES
Type
TA = Class
Class procedure DoIt; virtual;
Class Procedure DoitStatic; static;
end;
TB = CLass(TA)
Class procedure DoIt; override;
end;
begin
Writeln(’TA.Doit : ’,Self.ClassName);
end;
begin
Doit;
Writeln(’TA.DoitStatic : ’,ClassName);
end;
begin
Inherited;
Writeln(’TB.Doit : ’,Self.ClassName);
end;
begin
Writeln(’Through static method:’);
TB.DoItStatic;
Writeln(’Through class method:’);
TB.Doit;
end.
For the static class method, even though it was called using TB, the class (Self, if it were available)
94
CHAPTER 6. CLASSES
is set to TA, the class in which the static method was defined. For the class method, the class is set to
the actual class used to call the method (TB).
The method implementation of a message function is not different from an ordinary method. It is also
possible to call a message method directly, but this should not be done. Instead, the TObject.Dispatch
method should be used. Message methods are automatically virtual, i.e. they can be overridden in
descendent classes.
The TObject.Dispatch method can be used to call a message handler. It is declared in the
system unit and will accept a var parameter which must have at the first position a cardinal with the
message ID that should be called. For example:
Type
TMsg = Record
MSGID : Cardinal;
Data : Pointer;
Var
Msg : TMSg;
MyObject.Dispatch (Msg);
In this example, the Dispatch method will look at the object and all its ancestors (starting at the
object, and searching up the inheritance class tree), to see if a message method with message MSGID
has been declared. If such a method is found, it is called, and passed the Msg parameter.
If no such method is found, DefaultHandler is called. DefaultHandler is a virtual method
of TObject that doesn’t do anything, but which can be overridden to provide any processing that
might be needed. DefaultHandler is declared as follows:
In addition to the message method with a Integer identifier, Free Pascal also supports a message
method with a string identifier:
The working of the string message handler is the same as the ordinary integer message handler:
The TObject.DispatchStr method can be used to call a message handler. It is declared in
the system unit and will accept one parameter which must have at the first position a short string
with the message ID that should be called. For example:
95
CHAPTER 6. CLASSES
Type
TMsg = Record
MsgStr : String[10]; // Arbitrary length up to 255 characters.
Data : Pointer;
Var
Msg : TMSg;
MyObject.DispatchStr (Msg);
In this example, the DispatchStr method will look at the object and all its ancestors (starting at
the object, and searching up the inheritance class tree), to see if a message method with message
MsgStr has been declared. If such a method is found, it is called, and passed the Msg parameter.
If no such method is found, DefaultHandlerStr is called. DefaultHandlerStr is a virtual
method of TObject that doesn’t do anything, but which can be overridden to provide any processing
that might be needed. DefaultHandlerStr is declared as follows:
When encountering such a method, the compiler will generate code that loads the Self parameter
into the object instance pointer. The result of this is that it is possible to pass Self as a parameter to
such a method.
Remark: The type of the Self parameter must be of the same class as the class the method is defined in.
Type
TMyClass = Class(TComponent)
Constructor Create(AOwner : TComponent); override;
end;
begin
Inherited;
// Do more things
end;
In the above example, the Inherited statement will call Create of TComponent, passing it
AOwner as a parameter: the same parameters that were passed to the current method will be passed
to the parent’s method. They must not be specified again: if none are specified, the compiler will
pass the same arguments as the ones received.
The second case is slightly more complicated:
96
CHAPTER 6. CLASSES
Type
TMyClass = Class(TComponent)
Constructor Create(AOwner : TComponent); override;
Constructor CreateNew(AOwner : TComponent; DoExtra : Boolean);
end;
The CreateNew method will first call TComponent.Create and will pass it AOwner as a
parameter. It will not call TMyClass.Create.
Although the examples were given using constructors, the use of inherited is not restricted to
constructors, it can be used for any procedure or function or destructor as well.
6.6 Properties
6.6.1 Definition
Classes can contain properties as part of their fields list. A property acts like a normal field, i.e. its
value can be retrieved or set, but it allows to redirect the access of the field through functions and
procedures. They provide a means to associate an action with an assignment of or a reading from
a class ’field’. This allows e.g. checking that a value is valid when assigning, or, when reading, it
allows to construct the value on the fly. Moreover, properties can be read-only or write only. The
prototype declaration of a property is as follows:
Properties
-
- property definition class property identifier -
property interface
- property specifiers hintdirective -
-
- property interface : type identifier -
property parameter list
- -
index integerconstant
-
- property parameter list [ parameter declaration ] -
6 ;
-
- property specifiers -
read specifier write specifier
implements specifier
- -
default specifier stored specifier defaultarraypropertyspecifier
97
CHAPTER 6. CLASSES
-
- read specifier read field or method -
-
- write specifier write field or method -
-
- implements specifier implements identifier -
6 ,
-
- default specifier default -
constant
nodefault
-
- stored specifier stored constant -
identifier
-
- field or method field identifier -
method identifier
-
- defaultarraypropertyspecifier ; default -
A read specifier is either the name of a field that contains the property, or the name of a
method function that has the same return type as the property type. In the case of a simple type, this
function must not accept an argument. In case of an array property, the function must accept a single
argument of the same type as the index. In case of an indexed property, it must accept a integer as an
argument.
A read specifier is optional, making the property write-only. Note that class methods cannot
be used as read specifiers.
A write specifier is optional: If there is no write specifier, the property is read-only.
A write specifier is either the name of a field, or the name of a method procedure that accepts as a sole
argument a variable of the same type as the property. In case of an array property, the procedure must
accept 2 arguments: the first argument must have the same type as the index, the second argument
must be of the same type as the property. Similarly, in case of an indexed property, the first parameter
must be an integer.
The section (private, published) in which the specified function or procedure resides is irrel-
evant. Usually, however, this will be a protected or private method.
For example, given the following declaration:
Type
MyClass = Class
Private
Field1 : Longint;
Field2 : Longint;
Field3 : Longint;
Procedure Sety (value : Longint);
Function Gety : Longint;
Function Getz : Longint;
Public
Property X : Longint Read Field1 write Field2;
Property Y : Longint Read GetY Write Sety;
Property Z : Longint Read GetZ;
end;
Var
MyClass : TMyClass;
98
CHAPTER 6. CLASSES
MyClass.Z := 0;
{$mode objfpc}
Type
TPoint = Class(TObject)
Private
FX,FY : Longint;
Function GetCoord (Index : Integer): Longint;
Procedure SetCoord (Index : Integer; Value : longint);
Public
Property X : Longint index 1 read GetCoord Write SetCoord;
Property Y : Longint index 2 read GetCoord Write SetCoord;
Property Coords[Index : Integer]:Longint Read GetCoord;
end;
99
CHAPTER 6. CLASSES
end;
end;
Var
P : TPoint;
begin
P := TPoint.create;
P.X := 2;
P.Y := 3;
With P do
WriteLn (’X=’,X,’ Y=’,Y);
end.
When the compiler encounters an assignment to X, then SetCoord is called with as first parameter
the index (1 in the above case) and with as a second parameter the value to be set. Conversely, when
reading the value of X, the compiler calls GetCoord and passes it index 1. Indexes can only be
integer values.
Type
TIntList = Class
Private
Function GetInt (I : Longint) : longint;
Function GetAsString (A : String) : String;
Procedure SetInt (I : Longint; Value : Longint;);
Procedure SetAsString (A : String; Value : String);
Public
Property Items [i : Longint] : Longint Read GetInt
Write SetInt;
Property StrItems [S : String] : String Read GetAsString
Write SetAsstring;
end;
Var
AIntList : TIntList;
AIntList.Items[26] := 1;
AIntList.StrItems[’twenty-five’] := ’zero’;
WriteLn (’Item 26 : ’,AIntList.Items[26]);
100
CHAPTER 6. CLASSES
AIntList.Items[’twenty-five’] := 1;
AIntList.StrItems[26] := ’zero’;
Type
TGrid = Class
Private
Function GetCell (I,J : Longint) : String;
Procedure SetCell (I,J : Longint; Value : String);
Public
Property Cellcs [Row,Col : Longint] : String Read GetCell
Write SetCell;
end;
If there are N dimensions, then the types of the first N arguments of the getter and setter must
correspond to the types of the N index specifiers in the array property definition.
AIntList.Items[26] := 1;
AIntList[26] := 1;
Only one default property per class is allowed, but descendent classes can redeclare the default
property.
101
CHAPTER 6. CLASSES
Only class-typed fields can be published. For properties, any simple property whose size is less
than or equal to a pointer, can be declared published: floats, integers, sets (with less than 32 distinct
elements), enumerateds, classes or dynamic arrays (not array properties).
Although run-time type information is available for other types, these types cannot be used for a prop-
erty or field definition in a published section. The information is present to describe f.e. arguments
of procedures or functions.
1. When the class is instantiated, the default value is not automatically applied to the property, it
is the responsibility-g of the programmer to do this in the constructor of the class.
2. The value 2147483648 cannot be used as a default value, as it is used internally to denote
nodefault.
3. It is not possible to specify a default for array properties.
The nodefault specifier (nodefault) must be used to indicate that a property has no default value.
The effect is that the value of this property is always written to the stream when streaming the
property.
type
TAncestor = class
private
FP1 : Integer;
public
property P: integer Read FP1 write FP1;
end;
TClassA = class(TAncestor)
private
procedure SetP(const AValue: char);
102
CHAPTER 6. CLASSES
begin
Inherited P:=Ord(AValue);
end;
begin
Result:=Char((Inherited P) and $FF);
end;
TClassA redefines P as a character property instead of an integer property, but uses the parents P
property to store the value.
Care must be taken when using virtual get/set routines for a property: setting the inherited property
still observes the normal rules of inheritance for methods. Consider the following example:
type
TAncestor = class
private
procedure SetP1(const AValue: integer); virtual;
public
property P: integer write SetP1;
end;
TClassA = class(TAncestor)
private
procedure SetP1(const AValue: integer); override;
procedure SetP2(const AValue: char);
public
constructor Create;
property P: char write SetP2;
end;
constructor TClassA.Create;
begin
inherited P:=3;
end;
In this case, when setting the inherited property P, the implementation TClassA.SetP1 will be
called, because the SetP1 method is overridden.
If the parent class implementation of SetP1 must be called, then this must be called explicitly:
constructor TClassA.Create;
begin
inherited SetP1(3);
end;
103
CHAPTER 6. CLASSES
TA = Class(TObject)
Private
class var myprivatea : integer;
class Function GetB : Integer; static;
class Procedure SetA(AValue : Integer); static;
class Procedure SetB(AValue : Integer); static;
public
Class property MyA : Integer Read MyPrivateA Write SetA;
Class property MyA : Integer Read GetB Write SetB;
end;
The reason for the requirement is that a class property is associated to the particular class in which
it is defined, but not to descendent classes. Since class methods can be virtual, this would allow
descendent classes to override the method, making them unsuitable for class property access.
type
TA = Class(TObject)
Public
Type TEnum = (a,b,c);
Class Function DoSomething : TEnum;
end;
begin
Result:=a;
end;
var
E : TA.TEnum;
104
CHAPTER 6. CLASSES
begin
E:=TA.DoSomething;
end.
Whereas
type
TA = Class(TObject)
Strict Private
Type TEnum = (a,b,c);
Public
Class Function DoSomething : TEnum;
end;
begin
Result:=a;
end;
var
E : TA.TEnum;
begin
E:=TA.DoSomething;
end.
105
Chapter 7
Interfaces
7.1 Definition
As of version 1.1, FPC supports interfaces. Interfaces are an alternative to multiple inheritance
(where a class can have multiple parent classes) as implemented for instance in C++. An interface
is basically a named set of methods and properties: a class that implements the interface provides
all the methods as they are enumerated in the Interface definition. It is not possible for a class to
implement only part of the interface: it is all or nothing.
Interfaces can also be ordered in a hierarchy, exactly as classes: an interface definition that inherits
from another interface definition contains all the methods from the parent interface, as well as the
methods explicitly named in the interface definition. A class implementing an interface must then
implement all members of the interface as well as the methods of the parent interface(s).
An interface can be uniquely identified by a GUID. GUID is an acronym for Globally Unique Iden-
tifier, a 128-bit integer guaranteed always to be unique1 . Especially on Windows systems, the GUID
of an interface can and must be used when using COM.
The definition of an Interface has the following form:
Interface type
-
- Interface end -
heritage [’ GUID ’] component list
-
- heritage ( interface type identifier ) -
-
- component list method definition -
6 property definition
106
CHAPTER 7. INTERFACES
• The properties declared in an interface can only have methods as read and write specifiers.
• There are no constructors or destructors. Instances of interfaces cannot be created directly:
instead, an instance of a class implementing the interface must be created.
• Only calling convention modifiers may be present in the definition of a method. Modifiers
as virtual, abstract or dynamic, and hence also override cannot be present in the
interface definition.
IMyInterface = Interface
Function MyFunc : Integer;
Function MySecondFunc : Integer;
end;
[’{HHHHHHHH-HHHH-HHHH-HHHH-HHHHHHHHHHHH}’]
Each H character represents a hexadecimal number (0-9,A-F). The format contains 8-4-4-4-12 num-
bers. A GUID can also be represented by the following record, defined in the objpas unit (included
automatically when in DELPHI or OBJFPC mode):
PGuid = ^TGuid;
TGuid = packed record
case integer of
1 : (
Data1 : DWord;
Data2 : word;
Data3 : word;
Data4 : array[0..7] of byte;
);
2 : (
D1 : DWord;
D2 : word;
D3 : word;
D4 : array[0..7] of byte;
);
3 : ( { uuid fields according to RFC4122 }
time_low : dword;
107
CHAPTER 7. INTERFACES
time_mid : word;
time_hi_and_version : word;
clock_seq_hi_and_reserved : byte;
clock_seq_low : byte;
node : array[0..5] of byte;
);
end;
{$mode objfpc}
program testuid;
Const
MyGUID : TGUID = ’{10101010-1010-0101-1001-110110110110}’;
begin
end.
Normally, the GUIDs are only used in Windows, when using COM interfaces. More on this in the
next section.
Type
IMyInterface = Interface
Function MyFunc : Integer;
Function MySecondFunc : Integer;
end;
TMyClass = Class(TInterfacedObject,IMyInterface)
Function MyFunc : Integer;
Function MyOtherFunc : Integer;
end;
begin
Result:=23;
end;
begin
Result:=24;
end;
108
CHAPTER 7. INTERFACES
Normally, the names of the methods that implement an interface, must equal the names of the meth-
ods in the interface definition.
However, it is possible to provide aliases for methods that make up an interface: that is, the compiler
can be told that a method of an interface is implemented by an existing method with a different name.
This is done as follows:
Type
IMyInterface = Interface
Function MyFunc : Integer;
end;
TMyClass = Class(TInterfacedObject,IMyInterface)
Function MyOtherFunction : Integer;
Function IMyInterface.MyFunc = MyOtherFunction;
end;
This declaration tells the compiler that the MyFunc method of the IMyInterface interface is
implemented in the MyOtherFunction method of the TMyClass class.
type
IMyInterface = interface
procedure P1;
end;
The interface should not necessarily be in a field, any read identifier can be used.
If the interface is implemented by a delegate object, (a helper object that actually implements the
interface) then it can be used as well with the implements keyword:
{$interfaces corba}
type
109
CHAPTER 7. INTERFACES
IMyInterface = interface
procedure P1;
end;
Note that in difference with Delphi, the delegate class must explicitly specify the interface: the
compiler will not search for the methods in the delegate class, it will simply check if the delegate
class implements the specified interface.
It is possible to implement multiple interfaces using a single delegated object:
{$interfaces corba}
type
IMyInterface = interface
procedure P1;
end;
IMyInterface1 = interface
procedure P2;
end;
It is not possible to mix method resolution and interface delegation. That means, it is not possible
to implement part of an interface through method resolution and implement part of the interface
through delegation. The following attempts to implement IMyInterface partly through method
resolution (P1), and partly through delegation. The compiler will not accept the following code:
{$interfaces corba}
type
IMyInterface = interface
procedure P1;
110
CHAPTER 7. INTERFACES
procedure P2;
end;
However, it is possible to implement one interface through method resolution, and another through
delegation:
{$interfaces corba}
type
IMyInterface = interface
procedure P1;
end;
IMyInterface2 = interface
procedure P2;
end;
TMyClass = class(TInterfacedObject,
IMyInterface, IMyInterface2)
FI2 : IMyInterface2;
protected
procedure IMyInterface.P1 = MyP1;
procedure MyP1;
public
property MyInterface: IMyInterface2
read FI2 implements IMyInterface2;
end;
Note that interface delegation can be used to specify that a class implements parent interfaces:
IGMGetFileName = interface(IUnknown)
[’{D3ECCB42-A563-4cc4-B375-79931031ECBA}’]
function GetFileName: String; stdcall;
property FileName: String read GetFileName;
end;
IGMGetSetFileName = Interface(IGMGetFileName)
[’{ECFB879F-86F6-41a3-A685-0C899A2B5BCA}’]
procedure SetFileName(const Value: String); stdcall;
property FileName: String read GetFileName write SetFileName;
end;
111
CHAPTER 7. INTERFACES
Var
112
CHAPTER 7. INTERFACES
B : AClass;
begin
// ...
AInterface(B.Intf).testproc;
// ...
end;
Assume the interface intf is reference counted. When the compiler evaluates B.Intf, it creates a
temporary variable. This variable may be released only when the procedure exits: it is therefor invalid
to e.g. free the instance B prior to the exit of the procedure, since when the temporary variable is
finalized, it will attempt to free B again.
Additionally, function results may point to a non-nil valid COM interface on entry: this is because
the function result is treated as a var parameter.
113
Chapter 8
Generics
8.1 Introduction
Generics are templates for generating other types. These can be classes, objects, interfaces and even
functions, arrays, records. It is a concept that comes from C++, where it is deeply integrated in the
language. As of version 2.2, Free Pascal also officially has support for templates or Generics. They
are implemented as a kind of macro which is stored in the unit files that the compiler generates, and
which is replayed as soon as a generic class is specialized.
Creating and using generics is a 2-phase process.
1. The definition of the generic is defined as a new type: this is a code template, a macro which
can be replayed by the compiler at a later stage.
2. A generic type is specialized: this defines a second type, which is a specific implementation of
the generic type: the compiler replays the macro which was stored when the generic type was
defined.
There are several units distributed with free pascal that implement generic containers and classes.
For example the fgl unit.
-
- template list identifier list -
6 ;
114
CHAPTER 8. GENERICS
-
- identifier list identifier -
6 , : type identifier
6 ,
class
interface
object
record
-
- generic type class type -
object type
interface type
procedural type
record type
array type
For classes, objects, procedural types and extended records, the generic type declaration should be
followed by a type implementation. It is the same as a normal class implementation with a single
exception, namely that any identifier with the same name as one of the template identifiers must be a
type identifier.
So, the generic type declaration is much like a normal type declaration, except that there is an as yet
unknown type present. The unknown types are listed in the placeholder list, and they are unknown
until the class is specialized.
The following is a valid generic class definition:
Type
generic TList<_T>=class(TObject)
Public
type
TCompareFunc = function(const Item1, Item2: _T): Integer;
var
data : _T;
procedure Add(item: _T);
procedure Sort(compare: TCompareFunc);
end;
There are some noteworthy things about this declaration and implementation:
1. There is a single placeholder _T. It will be substituted by a type identifier when the generic
class is specialized. The identifier _T may not be used for anything else than a type place-
holder. This means that the following would be invalid:
115
CHAPTER 8. GENERICS
Var
_t : integer;
begin
// do something.
end;
2. The local type block contains a single type TCompareFunc. Note that the actual type is not
yet known inside the generic class definition: the definition contains a reference to the place-
holder _T. All other identifier references must be known when the generic class is defined, not
when the generic class is specialized.
3. The local variable block is equivalent to the following:
generic TList<_T>=class(TObject)
Public
type
TCompareFunc = function(const Item1, Item2: _T): Integer;
Public
data : _T;
procedure Add(item: _T);
procedure Sort(compare: TCompareFunc);
end;
Not only generic classes can be defined, but also other types:
{$mode objfpc}
{$INTERFACES CORBA}
type
116
CHAPTER 8. GENERICS
Remark: A word on visibility: the template types T or _T are available as strict private types. That means that
the types are not available in the descendent classes, unless they are made available through some
protected or private mechanism, as in the following example:
generic TList<_T>=class(TObject)
public type
TItemType = _T;
end;
Specialized type
-
- specialized type specialize identifier < type identifier list > -
-
- type identifier list identifier -
6 ,
Which is a very simple definition. Given the declaration of TList in the previous section, the
following would be a valid type definition:
Type
TPointerList = specialize TList<Pointer>;
TIntegerList = specialize TList<Integer>;
117
CHAPTER 8. GENERICS
As of version 3.0 of Free Pascal, the specialize keyword can also be used in a variable declaration:
Var
P : specialize TList<Pointer>;
The type in the specialize statement must be known, except in another generic type definition. Given
the 2 generic class definitions:
type
Generic TMyFirstType<T1> = Class(TMyObject);
Generic TMySecondType<T2> = Class(TMyOtherObject);
type
TMySpecialType = specialize TMySecondType<TMyFirstType>;
because the type TMyFirstType is a generic type, and thus not fully defined. The compiler will
complain:
type
TA = specialize TMyFirstType<Atype>;
TB = specialize TMySecondType<TA>;
and
In these definitions, the specialization is only performed when the generic type itself is specialized,
and at that time, the types are known.
Remark: As of version 3.0, it is possible to make a forward definition of a generic class. In prior versions the
compiler would generate an error if a forward declaration of a class was later defined as a generic
specialization. This means that the following is now possible:
{$mode objfpc}
Type
TMyClass = Class;
// Other declarations
118
CHAPTER 8. GENERICS
{$mode objfpc}
{$h+}
uses sysutils, classes;
Type
generic TList<_T : TComponent> = class(TObject)
public
Type TCompareFunc = function(const Item1, Item2: _T): Integer;
Public
data : _T;
procedure Add(item: _T);
procedure Sort(compare: TCompareFunc);
end;
Type
generic TList<Key1,Key2 : TComponent; Value1 : TObject> = class(TObject)
Additionally, it is possible to specify more than one type identifier for class and interface type re-
strictions. If a class is specified, then the type used for the template must be equal to or descend from
the indicated type:
Type
generic TList<T: TComponent, IEnumerable> = class(TObject)
A class used to specialize T must descend from TComponent and must implement IEnumerable.
If an interface is specified, then the template type must implement at least this interface, but it can
also be a descendent interface from this interface:
Type
generic TGenList<T: IEnumerable> = class(TObject)
119
CHAPTER 8. GENERICS
end;
Multiple interfaces can be specified, in that case the class type must implement all listed interfaces:
It is possible to mix one class name with several interface names.
If no type restrictions are in effect, the compiler will assume that template types are not assignment
compatible.
This is specially important when the generic class contains overloaded methods. Given the following
generic type declaration:
type
generic TTest<T1, T2> = class
procedure Test(aArg: LongInt);
procedure Test(aArg: T1);
procedure Test(aArg: T2);
end;
Specializing the above will compile if T1 and T2 are of two different types and neither is also
LongInt. The following will compile:
or
Type
TTest<T> = Class(TObject)
Private
FObj : T;
Public
Property Obj : T Read FObj Write FObj;
end;
TIntegerTest = TTest<Integer>;
120
CHAPTER 8. GENERICS
In difference with Mode Objfpc, the template type names must be repeated in method definitions.
Type
TTest<T> = Class(TObject)
Private
FObj : T;
Public
Procedure DoIt;
Property Obj : T Read FObj Write FObj;
end;
Procedure TTest<T>.DoIt;
begin
end;
This requirement is directly related to the generic type overload capability mentioned in the next
section.
Type
generic TList<_T : record> = class(TObject)
public
Type TCompareFunc = function(const Item1, Item2: _T): Integer;
Public
data : _T;
procedure Add(item: _T);
procedure Sort(compare: TCompareFunc);
end;
TIntList = TList<Integer>;
Type
TTest<T> = Class(TObject)
Private
FObj : T;
Public
Property Obj : T Read FObj Write FObj;
end;
TTest<T,S> = Class(TObject)
Private
FObj1 : T;
FObj2 : S;
Public
121
CHAPTER 8. GENERICS
Type
TTest<T> = Class(TObject)
Private
FObj : T;
Public
Property Obj : T Read FObj Write FObj;
end;
Var
TTest : Integer;
var
t: TTest<LongInt>;
begin
t := TTest<LongInt>.Create;
end;
{$mode objfpc}
unit ua;
interface
type
Generic TMyClass<T> = Class(TObject)
Procedure DoSomething(A : T; B : INteger);
end;
122
CHAPTER 8. GENERICS
Implementation
begin
// Some code.
end;
end.
{$mode objfpc}
unit ub;
interface
uses ua;
Type
TB = Specialize TMyClass<string>;
implementation
end.
{$mode objfpc}
unit uc;
interface
uses ua;
Type
TB = Specialize TMyClass<string>;
implementation
end.
{$mode objfpc}
unit ud;
interface
uses ua,ub,uc;
Var
B : ub.TB;
C : uc.TB;
123
CHAPTER 8. GENERICS
implementation
begin
B:=C;
end.
The types ub.TB and uc.TB are assignment compatible. It does not matter that the types are defined
in different units. They could be defined in the same unit as well:
{$mode objfpc}
unit ue;
interface
uses ua;
Type
TB = Specialize TMyClass<string>;
TC = Specialize TMyClass<string>;
Var
B : TB;
C : TC;
implementation
begin
B:=C;
end.
Each specialization of a generic class with the same types as parameters is a new, distinct type, but
these types are assignment compatible if the template types used to specialize them are equal.
If the specialization is with a different template type, the types are still distinct, but no longer assign-
ment compatible. i.e. the following will not compile:
{$mode objfpc}
unit uf;
interface
uses ua;
Type
TB = Specialize TMyClass<string>;
TC = Specialize TMyClass<integer>;
Var
B : TB;
C : TC;
implementation
124
CHAPTER 8. GENERICS
begin
B:=C;
end.
type
generic TTest<T> = class
procedure Test;
end;
The following code will correctly initialize the variable myt during specialization:
procedure TTest.Test;
var
myt: T;
begin
// will have the correct Default if class is specialized
myt := Default(T);
end;
{$mode objfpc}
unit myunit;
interface
type
Generic TMyClass<T> = Class(TObject)
Procedure DoSomething(A : T; B : TSomeType);
end;
Type
TSomeType = Integer;
TSomeTypeClass = specialize TMyClass<TSomeType>;
125
CHAPTER 8. GENERICS
Implementation
begin
// Some code.
end;
end.
The above code will result in an error, because the type TSomeType is not known when the decla-
ration is parsed:
The second way in which this is visible, is the following. Assume a unit
{$mode objfpc}
unit mya;
interface
type
Generic TMyClass<T> = Class(TObject)
Procedure DoSomething(A : T);
end;
Implementation
Procedure DoLocalThings;
begin
Writeln(’mya.DoLocalThings’);
end;
begin
DoLocalThings;
end;
end.
The compiler will not allow to compile this unit, since the DoLocalThings function will not be
visible when the generic type is specialized:
Now, if the unit is modified, and the DoLocalThings function is moved to the interface section,
the unit will compile. When using this generic in a program:
126
CHAPTER 8. GENERICS
{$mode objfpc}
program myb;
uses mya;
procedure DoLocalThings;
begin
Writeln(’myb.DoLocalThings’);
end;
Type
TB = specialize TMyClass<Integer>;
Var
B : TB;
begin
B:=TB.Create;
B.DoSomething(1);
end.
Despite the fact that generics act as a macro which is replayed at specialization time, the reference
to DoLocalThings is resolved when TMyClass is defined, not when TB is defined. This means
that the output of the program is:
1. A programmer specializing a class has no way of knowing which local procedures are used, so
he cannot accidentally ’override’ it.
2. A programmer specializing a class has no way of knowing which local procedures are used, so
he cannot implement it either, since he does not know the parameters.
3. If implementation procedures are used as in the example above, they cannot be referenced from
outside the unit. They could be in another unit altogether, and the programmer has no way of
knowing he should include them before specializing his class.
{$mode objfpc}
unit mya;
interface
type
127
CHAPTER 8. GENERICS
Implementation
Function TMyClass.Add(A,B : T) : T;
begin
Result:=A+B;
end;
end.
When the compiler replays the generics macro, the addition must be possible. For a specialization
like this:
begin
Result:=A+B;
end;
The compiler knows how to add 2 integers, so this code will compile without problems. But the
following code:
Type
TComplex = record
Re,Im : Double;
end;
Type
TMyIntegerClass = specialize TMyClass<TComplex>;
Will not compile, unless the addition of 2 TComplex types is defined. This can be done using record
operators:
{$modeswitch advancedrecords}
uses mya;
Type
TComplex = record
Re,Im : Double;
class operator +(a,b : TComplex) : TComplex;
end;
begin
Result.re:=A.re+B.re;
128
CHAPTER 8. GENERICS
Result.im:=A.im+B.im;
end;
Type
TMyComplexClass = specialize TMyClass<TComplex>;
begin
// Code here
end.
Currently, due to an implementation restriction, it will not work using a global operator, i.e. the
following does not work yet:
uses mya;
Type
TComplex = record
Re,Im : Double;
end;
begin
Result.re:=A.re+B.re;
Result.im:=A.im+B.im;
end;
Type
TMyComplexClass = specialize TMyClass<TComplex>;
begin
// Code here
end.
129
Chapter 9
Extended records
9.1 Definition
Extended records are in many ways equivalent to objects and to a lesser extent to classes: they are
records which have methods associated with them, and properties. Like objects, when defined as a
variable they are allocated on the stack. They do not need to have a constructor. Extended records
have limitations over objects and classes in that they do not allow inheritance and polymorphism. It
is impossible to create a descendant record of a record1 .
Why then introduce extended records ? They were introduced by Delphi 2005 to support one of the
features introduced by .NET. Delphi deprecated the old TP style of objects, and re-introduced the
features of .NET as extended records. Free Pascal aims to be Delphi compatible, so extended records
are allowed in Free Pascal as well, but only in Delphi mode.
If extended records are desired in ObjFPC mode, then a mode switch must be used:
{$mode objfpc}
{$modeswitch advancedrecords}
Compatibility is not the only reason for introducing extended records. There are some practical
reasons for using methods or properties in records:
1. It is more in line with an object-oriented approach to programming: the type also contains any
methods that work on it.
2. In contrast with a procedural approach, putting all operations that work on a record in the
record itself, allows an IDE to show the available methods on the record when it is displaying
code completion options.
-
- record component list end -
packed 6
1 although it can be enhanced using record helpers, more about this in the chapter on record helpers.
130
CHAPTER 9. EXTENDED RECORDS
-
- component list -
record visibility specifier field definition
6
- variant part -
record method definition property definition
6 6
-
- field definition identifier list : type ; -
-
- record visibility specifier private -
strict
public
-
- record method definition function header ; -
procedure header call modifiers ;
Some of the restrictions when compared to classes or objects are obvious from the syntax diagram:
• No inheritance of records.
• No published and protected section exists.
• Constructors or destructors cannot be defined.
• Class methods (if one can name them so) require the static keyword.
• Methods cannot be virtual or abstract - this is a consequence of the fact that there is no inheri-
tance.
Other than that the definition much resembles that of a class or object.
Remark: In the case of a variant record, the Case keyword implicitly starts a var section, meaning class
variables or methods are not allowed in the variant part of the record.
The following are few examples of valid extended record definitions:
TTest1 = record
a : integer;
function Test(aRecurse: Boolean): Integer;
end;
TTest2 = record
private
A,b : integer;
public
procedure setA(AValue : integer);
property SafeA : Integer Read A Write SetA;
end;
131
CHAPTER 9. EXTENDED RECORDS
end;
TTest4 = record
private
a : Integer;
protected
function getp : integer;
public
b : string;
procedure setp (aValue : integer);
property p : integer read Getp Write SetP;
public
case x : integer of
1 : (Q : string);
2 : (S : String);
end;
Note that it is possible to specify a visibility for the members of the record. This is particularly useful
for example when creating an interface to a C library: the actual fields can be declared hidden, and
more ’pascal’ like properties can be exposed which act as the actual fields. The TTest3 record
definition shows that the packed directive can be used in extended records. Extended records have
the same memory layout as their regular counterparts: the methods and properties are not part of the
record structure in memory.
The TTest4 record definition in the above examples shows that the extended record still has the
ability to define a variant part. As with the regular record, the variant part must come last. It cannot
contain methods.
type
TIntArray = array[0..3] of Integer;
TEnumerator = record
private
FIndex: Integer;
FArray: TIntArray;
function GetCurrent: Integer;
public
function MoveNext: Boolean;
property Current: Integer read GetCurrent;
end;
TMyArray = record
F: array[0..3] of Integer;
function GetEnumerator: TEnumerator;
end;
132
CHAPTER 9. EXTENDED RECORDS
inc(FIndex);
Result := FIndex < Length(FArray);
end;
After these definitions, the following code will compile and enumerate all elements in F:
var
Arr: TMyArray;
I: Integer;
begin
for I in Arr do
WriteLn(I);
end.
type
TIntArray = array[0..3] of Integer;
TEnumerator = record
private
FIndex: Integer;
FArray: TIntArray;
function GetCurrent: Integer;
public
function MoveNext: Boolean;
property Current: Integer read GetCurrent;
end;
TMyArray = record
F: array[0..3] of Integer;
end;
133
CHAPTER 9. EXTENDED RECORDS
134
Chapter 10
10.1 Definition
Class, record and type helpers can be used to add methods to an existing class, record or simple type,
without making a derivation of the class or re-declaring the record.
For a record or a simple type, the type helper acts as if record or the simple type is a class, and
methods are declared for it. Inside the methods, Self will refer to the value of the record or simple
type.
For classes, the effect is like inserting a method in the method table of the class. If the helper
declaration is in the current scope of the code, then the methods and properties of the helper can be
used as if they were part of the class declaration for the class or record that the helper extends.
The syntax diagram for a class, record or type helper is presented below:
Helper type
-
- class helper for Identifier helper component list -
record ( basehelper ) 6
type
- end hint modifiers -
-
- helper component list method definition -
property definition
The diagram shows that a helper definition looks very much like a regular class definition. It simply
declares some extra constructors, methods, properties and fields for a class: the class, record or
simple type for which the helper is an extension is indicated after the for keyword.
Since an enumerator for a class is obtained through a regular method, class helpers can also be used
to override the enumerators for the class.
As can be seen from the syntax diagram, it is possible to create descendants of helpers: the helpers
can form a hierarchy of their own, allowing to override methods of a parent helper. They also have
visibility specifiers, just like records and classes.
As in an instance of the class, the Self identifier in a method of a class helper refers to the class
instance (not the helper instance). For a record, it refers to the record.
135
CHAPTER 10. CLASS, RECORD AND TYPE HELPERS
The following is a simple class helper for the TObject class, which provides an alternate version
of the standard ToString method.
var
o: TObject;
begin
Writeln(o.AsString(’The object’’s name is %s’));
end.
Remark: The helper modifier is only a modifier just after the class or record keywords. That means
that the first member of a class or record cannot be named helper. A member of a class or record
can be called helper, it just cannot be the first one, unless it is escaped with a &, as for all identifiers
that match a keyword.
Remark: Support for type helpers requires the use of Delphi mode or the use of a typehelpers modeswitch
in other modes:
{$MODESWITCH TYPEHELPERS}
Remark: Support for record helpers requires the use of Delphi mode or the use of a advancedrecords
modeswitch in other modes:
{$MODESWITCH ADVANCEDRECORDS}
136
CHAPTER 10. CLASS, RECORD AND TYPE HELPERS
The following modifies the previous example by overloading the ToString method:
var
o: TObject;
begin
Writeln(o.ToString(’The object’’s name is %s’));
end.
• A record helper cannot be used to extend a class. The following will fail:
• Inside a helper’s declaration the methods/fields of the extended record can’t be accessed in e.g.
a property definition. They can be accessed in the implementation, of course. This means that
the following will not compile:
TTest = record
Test: Integer;
end;
• Record helpers can only access public fields (in case an extended record with visibility speci-
fiers is used).
• Inheritance of record helpers is only allowed in ObjFPC mode; In Delphi mode, it is not
allowed.
• Record helpers can only descend from other record helpers, not from class helpers.
• Unlike class helpers, a descendent record helper must extend the same record type.
• In Delphi mode, it is not possible to call the extended record’s method using inherited. It
is possible to do so in ObjFPC mode. The following code needs ObjFPC mode to compile:
type
TTest = record
137
CHAPTER 10. CLASS, RECORD AND TYPE HELPERS
• Support for type helpers needs to be activated using the modeswitch typehelpers:
{$modeswitch typehelpers}
• In Delphi (and DelphiUnicode) mode, for stricter Delphi compatibility, the record helpers must
be used instead of a type helper.
• The modes ObjFPC and MacPas use type helper, but the modeswitch TypeHelpers must be
used.
138
CHAPTER 10. CLASS, RECORD AND TYPE HELPERS
• Type helpers can only descend from other type helpers, not from class or record helpers.
• A descendent type helper must extend the same type.
{$mode objpas}
{$modeswitch typehelpers}
type
TLongIntHelper = type helper for LongInt
constructor create(AValue: LongInt);
class procedure Test; static;
procedure DoPrint;
end;
begin
Self:=Avalue;
DoPrint;
end;
begin
Writeln(’Test’);
end;
procedure TLongIntHelper.DoPrint;
begin
Writeln(’Value :’,Self);
end;
var
i: LongInt;
begin
I:=123;
i.Test;
$12345678.Test;
LongInt.Test;
I:=123;
i.DoPrint;
$12345678.DoPrint;
end.
10.5 A note on scope and lifetime for record and type helpers
For classes, the lifetime of an instance of a class is explicitly managed by the programmer. It is
therefor clear what the Self parameter means and when it is valid.
Records and other simple types are allocated on the stack, which means they go out of scope when
the function, procedure or method in which they are used, exits.
139
CHAPTER 10. CLASS, RECORD AND TYPE HELPERS
Combined with the fact that helper methods are type compatible to class methods, and can therefor
be used as event handlers, this can lead to surprising situations: The data pointer in a helper method
is set to the address of the variable.
Consider the following example:
{$mode objfpc}
{$modeswitch typehelpers}
uses
Classes;
type
TInt32Helper = type helper for Int32
procedure Foo(Sender: TObject);
end;
var
i: Int32 = 10;
m: TNotifyEvent;
begin
m := @i.Foo;
WriteLn(’Data : ’,PtrUInt(TMethod(m).Data));
m(nil);
end.
This will print something like (the actual value for data may differ):
Data : 6848896
10
{$mode objfpc}
{$modeswitch typehelpers}
uses
Classes;
type
TInt32Helper = type helper for Int32
procedure Foo(Sender: TObject);
end;
140
CHAPTER 10. CLASS, RECORD AND TYPE HELPERS
var
i: Int32 = 10;
begin
Result:[email protected];
end;
Var
m: TNotifyEvent;
begin
m := GetHandler;
WriteLn(PtrUInt(TMethod(m).Data));
m(nil);
end.
140727246638796
0
The actual output will depend on the architecture, but the point is that i is no longer in scope, making
the output of it’s value meaningless, and possibly even leading to access violations and program
crashes.
10.6 Inheritance
As noted in the previous section, it is possible to create descendants of helper classes. Since only
the last helper class in the current scope can be used, it is necessary to descend a helper class from
another one if methods of both helpers must be used. More on this in a subsequent section.
A descendent of a class helper can extend a different class than its parent. The following is a valid
class helper for TMyObject:
TMyObject = class(TObject)
end;
The TMyObjectHelper extends TObjectHelper, but does not extend the TObject class, it
only extends the TMyObject class.
Since records know no inheritance, it is obvious that descendants of record helpers can only extend
the same record.
Remark: For maximum delphi compatibility, it is impossible to create descendants of record helpers in Delphi
mode.
141
CHAPTER 10. CLASS, RECORD AND TYPE HELPERS
10.7 Usage
Once a helper class is defined, its methods can be used whenever the helper class is in scope. This
means that if it is defined in a separate unit, then this unit should be in the uses clause wherever the
methods of the helper class are used.
Consider the following unit:
{$mode objfpc}
{$h+}
unit oha;
interface
Type
TObjectHelper = class helper for TObject
function AsString(const aFormat: String): String;
end;
implementation
uses sysutils;
begin
Result := Format(aFormat, [ToString]);
end;
end.
Program Example113;
uses oha;
Var
o : TObject;
begin
O:=TObject.Create;
Writeln(O.AsString(’O as a string : %s’));
end.
{$mode objfpc}
{$h+}
unit ohb;
interface
142
CHAPTER 10. CLASS, RECORD AND TYPE HELPERS
Type
TAObjectHelper = class helper for TObject
function MemoryLocation: String;
end;
implementation
uses sysutils;
begin
Result := format(’%p’,[pointer(Self)]);
end;
end.
Program Example113;
uses oha,ohb;
Var
o : TObject;
begin
O:=TObject.Create;
Writeln(O.AsString(’O as a string : %s’));
Writeln(O.MemoryLocation);
end.
Then the compiler will complain that it does not know the method ’AsString’. This is because the
compiler stops looking for class helpers as soon as the first class helper is encountered. Since the
ohb unit comes last in the uses clause, the compiler will only use TAObjectHelper as the class
helper.
The solution is to re-implement unit ohb:
{$mode objfpc}
{$h+}
unit ohc;
interface
uses oha;
Type
TAObjectHelper = class helper(TObjectHelper) for TObject
function MemoryLocation: String;
end;
implementation
143
CHAPTER 10. CLASS, RECORD AND TYPE HELPERS
uses sysutils;
begin
Result := format(’%p’,[pointer(Self)]);
end;
end.
And after replacing unit ohb with ohc, the example program will compile and function as expected.
Note that it is not enough to include a unit with a class helper once in a project; The unit must be
included whenever the class helper is needed.
144
Chapter 11
Objective-Pascal Classes
11.1 Introduction
The preferred programming language to access Mac OS X system frameworks is Objective-C. In
order to fully realize the potential offered by system interfaces written in that language, a variant of
Object Pascal exists in the Free Pascal compiler that tries to offer the same functionality as Objective-
C. This variant is called Objective-Pascal.
The compiler has mode switches to enable the use of these Objective-C-related constructs. There
are 2 kinds of Objective-C language features, discerned by a version number: Objective-C 1.0 and
Objective-C 2.0.
The Objective-C 1.0 language features can be enabled by adding a modeswitch to the source file:
{$modeswitch objectivec1}
{$modeswitch objectivec2}
145
CHAPTER 11. OBJECTIVE-PASCAL CLASSES
-
- objcclass -
external
name string constant
- -
heritage end
component list
class visibility specifier
6
- heritage (
- ) -
objective-Cclass type identifier implemented protocols
-
- implemented protocols protocol identifier -
6 ,
-
- component list -
visibility specifier field definition
6
- -
class variable declaration part
6 method definition
property definition
-
- class variable declaration part class variable declaration part -
-
- field definition identifier list : type ; -
static;
-
- method definition function header ;-
class procedure header
- -
;
override
message string constant
-
- class visibility specifier -
private
strict
protected
public
As can be seen, the syntax is roughly equivalent to Object Pascal syntax, with some extensions.
In order to use Objective-C classes, an external modifier exists: this indicates to the compiler that the
class is implemented in an external object file or library, and that the definition is meant for import
purposes. The following is an example of an external Objective-C class definition:
146
CHAPTER 11. OBJECTIVE-PASCAL CLASSES
message ’addSubview:’;
procedure setAutoresizingMask(mask: NSUInteger);
message ’setAutoresizingMask:’;
procedure setAutoresizesSubviews(flag: LongBool);
message ’setAutoresizesSubviews:’;
procedure drawRect(dirtyRect: NSRect);
message ’drawRect:’;
end;
As can be seen, the class definition is not so different from an Object Pascal class definition; Only the
message directive is more prominently present: each Objective-C or Objective-Pascal method must
have a message name associated with it. In the above example, no external name was specified for
the class definition, meaning that the Pascal identifier is used as the name for the Objective-C class.
However, since Objective-C is not so strict in its naming conventions, sometimes an alias must be
created for an Objective-C class name that doesn’t obey the Pascal identifier rules.
The following example defines an Objective-C class which is implemented in Pascal:
MyView = objcclass(NSView)
public
data : Integer;
procedure customMessage(dirtyRect: NSRect);
message ’customMessage’;
procedure drawRect(dirtyRect: NSRect); override;
end;
The absence of the external keyword tells the compiler that the methods must be implemented
later in the source file: it will be treated much like a regular object pascal class. Note the presence
of the override directive: in Objective-C, all methods are virtual. In Object Pascal, overrid-
ing a virtual method must be done through the override directive. This has been extended to
Objective-C classes: it allows the compiler to verify the correctness of the definition.
Unless the class is implementing the method of a protocol (more about this in a subsequent section),
one of message or override is expected: all methods are virtual, and either a new method is
started (or re-introduced), or an existing is overridden. Only in the case of a method that is part of a
protocol, the method can be defined without message or override.
Note that the Objective-C class declaration may or may not specify a parent class. In Object Pas-
cal, omitting a parent class will automatically make the new class a descendant of TObject. In
Objective-C, this is not the case: the new class will be a new root class. However, Objective-C does
have a class which fullfills the function of generic root class: NSObject, which can be considered
the equivalent of TObject in Object Pascal. It has other root classes, but in general, Objective-
Pascal classes should descend from NSObject. If a new root class is constructed anyway, it must
implement the NSObjectProtocol - just as the NSObject class itself does.
Finally, objective-Pascal classes can have properties, but these properties are only usable in Pascal
code: the compiler currently does not export the properties in a way that makes them usable from
Objective-C.
147
CHAPTER 11. OBJECTIVE-PASCAL CLASSES
This is a formal declaration. It tells the compiler that MyExternalClass is an Objective-C class
type, but that there is no declaration of the class members. The type can be used in the remainder of
the unit, but its use is restricted to storage allocation (in a field or method parameter definition) and
assignment (much like a pointer).
As soon as the class definition is encountered, the compiler can enforce type compatibility.
The following unit uses a formal declaration:
unit ContainerClass;
{$mode objfpc}
{$modeswitch objectivec1}
interface
type
MyItemClass = objcclass external;
MyContainerClass = objcclass
private
item: MyItemClass;
public
function getItem: MyItemClass; message ’getItem’;
end;
implementation
end.
unit ItemClass;
{$mode objfpc}
{$modeswitch objectivec1}
interface
type
MyItemClass = objcclass(NSObject)
private
content : longint;
public
function initWithContent(c: longint): MyItemClass;
message ’initWithContent:’;
function getContent: longint;
message ’getContent’;
end;
148
CHAPTER 11. OBJECTIVE-PASCAL CLASSES
implementation
end.
If both units are used in a program, the compiler knows what the class is and can verify the correctness
of some assignments:
Program test;
{$mode objfpc}
{$modeswitch objectivec1}
uses
ItemClass, ContainerClass;
var
c: MyContainerClass;
l: longint;
begin
c:=MyContainerClass.alloc.init;
l:=c.getItem.getContent;
end.
1. Call the ’alloc’ method (send an ’alloc’ message): This is a class method of NSObject,
and returns a pointer to memory for the new instance. The use of alloc is a convention in
Objective-C.
2. Send an ’initXXX’ message. By convention, all classes have one or more ’InitXXX’ methods
that initializes all fields in the instance. This method will return the final instance pointer,
which may be Nil.
var
obj: NSObject;
begin
149
CHAPTER 11. OBJECTIVE-PASCAL CLASSES
By convention, the initXXX method will return Nil if initialization of some fields failed, so it is
imperative that the result of the function is tested.
Similarly, no privileged destructor exists; By convention, the dealloc method fullfills the cleanup
of the instances. This method can be overridden to perform any cleanup necessary. Like Destroy, it
should never be called directly, instead, the release method should be called instead: All instances
in Objective-C are reference counted, and release will only call dealloc if the reference count
reaches zero.
• Protocol methods can be marked optional, i.e. the class implementing the protocol can decide
not to implement these methods.
• Protocols can inherit from multiple other protocols.
Objective-C classes can indicate which protocols they implement in the class definition, as could be
seen in the syntax diagram for Objective-C classes.
The following diagram shows how to declare a protocol. It starts with the objcprotocol keyword:
Protocol type
-
- objcprotocol -
external heritage
name string constant
- protocol method list end -
-
- heritage ( protocol type identifier ) -
6 ,
-
- protocol method list method definition -
6 required
optional
As in the case of objective-Pascal classes, the external specifier tells the compiler that the decla-
ration is an import of a protocol defined elsewhere. For methods, almost the same rules apply as for
methods in the Objective-Pascal class declarations. The exception is that message specifiers must be
present.
The required and optional specifiers before a series of method declarations are optional. If
none is specified, required is assumed. The following is a definition of a protocol:
150
CHAPTER 11. OBJECTIVE-PASCAL CLASSES
type
MyProtocol = objccprotocol
// default is required
procedure aRequiredMethod;
message ’aRequiredMethod’;
optional
procedure anOptionalMethodWithPara(para: longint);
message ’anOptionalMethodWithPara:’;
procedure anotherOptionalMethod;
message ’anotherOptionalMethod’;
required
function aSecondRequiredMethod: longint;
message ’aSecondRequiredMethod’;
end;
MyClassImplementingProtocol = objcclass(NSObject,MyProtocol)
procedure aRequiredMethod;
procedure anOptionalMethodWithPara(para: longint);
function aSecondRequiredMethod: longint;
end;
Note that in the class declaration, the message specifier was omitted. The compiler (and runtime) can
deduce it from the protocol definition.
11.6 Categories
Similar to class helpers in Object Pascal, Objective-C has Categories. Categories allow to extend
classes without actually creating a descendant of these classes. However, Objective-C categories
provide more functionality than a class helper:
1. In Object Pascal, only 1 helper class can be in scope (the last one). In Objective-C, multiple
categories can be in scope at the same time for a particular class.
2. In Object Pascal, a helper method cannot change an existing method present in the original
class (but it can hide a method). In Objective-C, a category can also replace existing methods
in another class rather than only add new ones. Since all methods are virtual in Objective-C,
this also means that this method changes for all classes that inherit from the class in which the
method was replaced (unless they override it).
3. Object Pascal helpers cannot be used to add interfaces to existing classes. By contrast, an
Objective-C category can also implement protocols.
The definition of an objective-C class closely resembles a protocol definition, and is started with the
objccategory keyword:
Category type
-
- objccategory -
external heritage
name string constant
- category method list end -
151
CHAPTER 11. OBJECTIVE-PASCAL CLASSES
-
- heritage ( Objective Class type identifier protocol type identifier ) -
6 ,
-
- category method list method definition -
6 reintroduce
Note again the possibility of an alias for externally defined categories: objective-C 2.0 allows an
empty category name. Note that the reintroduce modifier must be used if an existing method is
being replaced rather than that a new method is being added.
When replacing a method, calling ’inherited’ will not call the original method of the class, but instead
will call the parent class’ implementation of the method.
The following is an example of a category definition:
MyProtocol = objcprotocol
procedure protocolmethod; message ’protocolmethod’;
end;
MyCategory = objccategory(NSObject,MyProtocol)
function hash: cuint; reintroduce;
procedure protocolmethod; // from MyProtocol.
class procedure newmethod; message ’newmethod’;
end;
Note that this declaration replaces the Hash method of every class that descends from NSObject
(unless it specifically overrides it).
152
CHAPTER 11. OBJECTIVE-PASCAL CLASSES
11.8 Selectors
A Selector in Objective-C can be seen as an equivalent to a procedural type in Object Pascal.
In difference with the procedural type, Objective-C has only 1 selector type: SEL. It is defined in
the objc unit - which is automatically included in the uses clause of any unit compiled with the
objectivec1 modeswitch.
To assign a value to a variable of type SEL, the objcselector method must be used:
{$modeswitch objectivec1}
var
a: SEL;
begin
a:=objcselector(’initiWithWidth:andHeight:’);
a:=objcselector(’myMethod’);
end.
The objc unit contains methods to manipulate and use the selector.
153
CHAPTER 11. OBJECTIVE-PASCAL CLASSES
This has been translated to Objective-Pascal using the existing for-in loop mechanism. Therefor,
the feature behaves identically in both languages. Note that it requires the Objective-C 2.0 mode
switch to be activated.
The following is an example of the use of for-in:
{$mode delphi}
{$modeswitch objectivec2}
uses
CocoaAll;
var
arr: NSMutableArray;
element: NSString;
pool: NSAutoreleasePool;
i: longint;
begin
pool:=NSAutoreleasePool.alloc.init;
arr:=NSMutableArray.arrayWithObjects(
NSSTR(’One’),
NSSTR(’Two’),
NSSTR(’Three’),
NSSTR(’Four’),
NSSTR(’Five’),
NSSTR(’Six’),
NSSTR(’Seven’),
nil);
i:=0;
for element in arr do
begin
inc(i);
if i=2 then
continue;
if i=5 then
break;
if i in [2,5..10] then
halt(1);
NSLog(NSSTR(’element: %@’),element);
end;
pool.release;
end.
154
Chapter 12
Expressions
Expressions occur in assignments or in tests. Expressions produce a value of a certain type. Expres-
sions are built with two components: operators and their operands. Usually an operator is binary, i.e.
it requires 2 operands. Binary operators occur always between the operands (as in X/Y). Sometimes
an operator is unary, i.e. it requires only one argument. A unary operator occurs always before the
operand, as in -X.
When using multiple operands in an expression, the precedence rules of table (12.1) are used.
When determining the precedence, the compiler uses the following rules:
1. In operations with unequal precedences the operands belong to the operator with the high-
est precedence. For example, in 5*3+7, the multiplication is higher in precedence than the
addition, so it is executed first. The result would be 22.
2. If parentheses are used in an expression, their contents is evaluated first. Thus, 5*(3+7)
would result in 50.
Remark: The order in which expressions of the same precedence are evaluated is not guaranteed to be left-
to-right. In general, no assumptions on which expression is evaluated first should be made in such a
case. The compiler will decide which expression to evaluate first based on optimization rules. Thus,
in the following expression:
a := g(3) + f(2);
f(2) may be executed before g(3). This behaviour is distinctly different from Delphi or Turbo
Pascal.
If one expression must be executed before the other, it is necessary to split up the statement using
temporary results:
155
CHAPTER 12. EXPRESSIONS
e1 := g(3);
a := e1 + f(2);
Remark: The exponentiation operator (**) is available for overloading, but is not defined on any of the
standard Pascal types (floats and/or integers).
Expressions
-
- expression simple expression -
< simple expression
<=
>
>=
=
<>
in
is
-
- simple expression term -
6 +
-
or
xor
GraphResult<>grError
(DoItToday=Yes) and (DoItTomorrow=No);
Day in Weekend
A + B
-Pi
ToBe or NotToBe
Terms
156
CHAPTER 12. EXPRESSIONS
-
- term factor -
6 *
/
div
mod
and
shl
shr
as
2 * Pi
A Div B
(DoItToday=Yes) and (DoItTomorrow=No);
Factors
-
- factor ( expression ) -
variable reference
function call
unsigned constant
not factor
sign factor
set constructor
value typecast
address factor
-
- unsigned constant unsigned number -
character string
constant identifier
Nil
Function calls
-
- function call function identifier -
method designator actual parameter list
qualified method designator
variable reference
-
- actual parameter list ( ) -
expression
6 ,
157
CHAPTER 12. EXPRESSIONS
The variable reference must be a procedural type variable reference. A method designator can
only be used inside the method of an object. A qualified method designator can be used outside
object methods too. The function that will get called is the function with a declared parameter list
that matches the actual parameter list. This means that
1. The number of actual parameters must equal the number of declared parameters (unless default
parameter values are used).
2. The types of the parameters must be compatible. For variable reference parameters, the pa-
rameter types must be exactly the same.
If no matching function is found, then the compiler will generate an error. Which error depends -
among other things - on whether the function is overloaded or not: i.e. multiple functions with the
same name, but different parameter lists.
There are cases when the compiler will not execute the function call in an expression. This is the
case when assigning a value to a procedural type variable, as in the following example in Delphi or
Turbo Pascal mode:
Type
FuncType = Function: Integer;
Var A : Integer;
Function AddOne : Integer;
begin
A := A+1;
AddOne := A;
end;
Var F : FuncType;
N : Integer;
begin
A := 0;
F := AddOne; { Assign AddOne to F, Don’t call AddOne}
N := AddOne; { N := 1 !!}
end.
In the above listing, the assignment to F will not cause the function AddOne to be called. The
assignment to N, however, will call AddOne.
Sometimes, the call is desired, for instance in recursion in that case, the call must be forced. This can
be done by adding the parenthesis to the function name:
function rd : char;
var
c : char;
begin
read(c);
if (c=’\’) then
c:=rd();
rd:=c;
end;
var ch : char;
158
CHAPTER 12. EXPRESSIONS
begin
ch:=rd;
writeln(ch);
end.
The above will read a character and print it. If the input is a backslash, a second character is read.
A problem with this syntax is the following construction:
If F = AddOne Then
DoSomethingHorrible;
Should the compiler compare the addresses of F and AddOne, or should it call both functions, and
compare the result? In fpc and objfpc mode this is solved by considering a procedural variable
as equivalent to a pointer. Thus the compiler will give a type mismatch error, since AddOne is
considered a call to a function with integer result, and F is a pointer.
How then, should one check whether F points to the function AddOne? To do this, one should use
the address operator @:
If F = @AddOne Then
WriteLn (’Functions are equal’);
The left hand side of the boolean expression is an address. The right hand side also, and so the
compiler compares 2 addresses. How to compare the values that both functions return ? By adding
an empty parameter list:
If F()=Addone then
WriteLn (’Functions return same values ’);
Remark that this last behaviour is not compatible with Delphi syntax. Switching on Delphi mode
will allow you to use Delphi syntax.
Set constructors
-
- set constructor [ ] -
set group
6 ,
-
- set group expression -
.. expression
All set groups and set elements must be of the same ordinal type. The empty set is denoted by [],
and it can be assigned to any type of set. A set group with a range [A..Z] makes all values in the
range a set element. The following are valid set constructors:
159
CHAPTER 12. EXPRESSIONS
[today,tomorrow]
[Monday..Friday,Sunday]
[ 2, 3*2, 6*2, 9*2 ]
[’A’..’Z’,’a’..’z’,’0’..’9’]
Remark: If the first range specifier has a bigger ordinal value than the second, the resulting set will be empty,
e.g., [’Z’..’A’] denotes an empty set. One should be careful when denoting a range.
Typecasts
-
- value typecast type identifier ( expression ) -
Value typecasts cannot be used on the left side of assignments, as variable typecasts. Here are some
valid typecasts:
Byte(’A’)
Char(48)
boolean(1)
longint(@Buffer)
In general, the type size of the expression and the size of the type cast must be the same. However, for
ordinal types (byte, char, word, boolean, enumerates) this is not so, they can be used interchangeably.
That is, the following will work, although the sizes do not match.
Integer(’A’);
Char(4875);
boolean(100);
Word(@Buffer);
Var
160
CHAPTER 12. EXPRESSIONS
C : Char;
B : Byte;
begin
B:=Byte(C);
Char(B):=C;
end;
Pointer variables can be typecasted to procedural types, but not to method pointers.
A typecast is an expression of the given type, which means the typecast can be followed by a qualifier:
Type
TWordRec = Packed Record
L,H : Byte;
end;
Var
P : Pointer;
W : Word;
S : String;
begin
TWordRec(W).L:=$FF;
TWordRec(W).H:=0;
S:=TObject(P).ClassName;
program me;
Var
A : packed Array[1..20] of Byte;
I : LongInt;
begin
For I:=1 to 20 do
A[I]:=I;
I:=PInteger(Unaligned(@A[13]))^;
end.
161
CHAPTER 12. EXPRESSIONS
Address factor
-
- addressfactor @ variable reference -
procedure identifier
function identifier
qualified method identifier
The @ operator returns a typed pointer if the $T switch is on. If the $T switch is off then the address
operator returns an untyped pointer, which is assignment compatible with all pointer types. The type
of the pointer is ˆT, where T is the type of the variable reference. For example, the following will
compile
Program tcast;
{$T-} { @ returns untyped pointer }
begin
PLargeBuffer := @Buffer;
end.
Changing the {$T-} to {$T+} will prevent the compiler from compiling this. It will give a type
mismatch error.
By default, the address operator returns an untyped pointer: applying the address operator to a func-
tion, method, or procedure identifier will give a pointer to the entry point of that function. The result
is an untyped pointer.
This means that the following will work:
Procedure MyProc;
begin
end;
Var
P : PChar;
begin
P:=@MyProc;
end;
By default, the address operator must be used if a value must be assigned to a procedural type
variable. This behaviour can be avoided by using the -Mtp or -MDelphi switches, which result in
a more compatible Delphi or Turbo Pascal syntax.
162
CHAPTER 12. EXPRESSIONS
12.8 Operators
Operators can be classified according to the type of expression they operate on. We will discuss them
type by type.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
Div Integer division
Mod Remainder
With the exception of Div and Mod, which accept only integer expressions as operands, all operators
accept real and integer expressions as operands.
For binary operators, the result type will be integer if both operands are integer type expressions. If
one of the operands is a real type expression, then the result is real.
As an exception, division (/) results always in real values.
Operator Operation
+ Sign identity
- Sign inversion
For unary operators, the result type is always equal to the expression type. The division (/) and Mod
operator will cause run-time errors if the second argument is zero.
The sign of the result of a Mod operator is the same as the sign of the left side operand of the Mod
operator. In fact, the Mod operator is equivalent to the following operation :
I mod J = I - (I div J) * J
163
CHAPTER 12. EXPRESSIONS
Operator Operation
not Bitwise negation (unary)
and Bitwise and
or Bitwise or
xor Bitwise xor
shl Bitwise shift to the left
shr Bitwise shift to the right
<< Bitwise shift to the left (same as shl)
>> Bitwise shift to the right (same as shr)
Operator Operation
not logical negation (unary)
and logical and
or logical or
xor logical xor
Remark: By default, boolean expressions are evaluated with short-circuit evaluation. This means that from
the moment the result of the complete expression is known, evaluation is stopped and the result is
returned. For instance, in the following expression:
B := True or MaybeTrue;
The compiler will never look at the value of MaybeTrue, since it is obvious that the expression will
always be True. As a result of this strategy, if MaybeTrue is a function, it will not get called !
(This can have surprising effects when used in conjunction with properties)
164
CHAPTER 12. EXPRESSIONS
Var
Dirname : PChar;
...
Dirname := Dirname+’\’;
Operator Action
+ Union
- Difference
* Intersection
>< Symmetric difference
<= Contains
include include an element in the set
exclude exclude an element from the set
in check wether an element is in a set
The set type of the operands must be the same, or an error will be generated by the compiler.
The following program gives some valid examples of set operations:
Type
Day = (mon,tue,wed,thu,fri,sat,sun);
Days = set of Day;
165
CHAPTER 12. EXPRESSIONS
Var
D : Day;
S : String;
begin
S:=’’;
For D:=Mon to Sun do
if D in W then
begin
If (S<>’’) then S:=S+’,’;
S:=S+DayNames[D];
end;
Writeln(’[’,S,’]’);
end;
Var
W : Days;
begin
W:=[mon,tue]+[wed,thu,fri]; // equals [mon,tue,wed,thu,fri]
PrintDays(W);
W:=[mon,tue,wed]-[wed]; // equals [mon,tue]
PrintDays(W);
W:=[mon,tue,wed]-[wed,thu]; // also equals [mon,tue]
PrintDays(W);
W:=[mon,tue,wed]*[wed,thu,fri]; // equals [wed]
PrintDays(W);
W:=[mon,tue,wed]><[wed,thu,fri]; // equals [mon,tue,thu,fri]
PrintDays(W);
end.
As can be seen, the union is equivalent to a binary OR, while the intersection is equivalent to a binary
AND, and the symmetric difference equals a XOR operation.
The Include and Exclude operations are equivalent to a union or a difference with a set of 1
element. Thus,
Include(W,wed);
is equivalent to
W:=W+[wed];
and
Exclude(W,wed);
is equivalent to
W:=W-[wed];
The In operation results in a True if the left operand (an element) is included of the right operand
(a set), the result will be False otherwise.
166
CHAPTER 12. EXPRESSIONS
Operator Action
= Equal
<> Not equal
< Strictly less than
> Strictly greater than
<= Less than or equal
>= Greater than or equal
in Element of
Normally, left and right operands must be of the same type. There are some notable exceptions,
where the compiler can handle mixed expressions:
Operator Action
is Checks class type
as Conditional typecast
An expression containing the is operator results in a boolean type. The is operator can only be
used with a class reference or a class instance. The usage of this operator is as follows:
Object is Class
Object.InheritsFrom(Class)
167
CHAPTER 12. EXPRESSIONS
Var
A : TObject;
B : TClass;
begin
if A is TComponent then ;
If A is B then;
end;
The as operator performs a conditional typecast. It results in an expression that has the type of the
class:
Object as Class
If Object=Nil then
Result:=Nil
else if Object is Class then
Result:=Class(Object)
else
Raise Exception.Create(SErrInvalidTypeCast);
Note that if the object is nil, the as operator does not generate an exception.
The following are some examples of the use of the as operator:
Var
C : TComponent;
O : TObject;
begin
(C as TEdit).Text:=’Some text’;
C:=O as TComponent;
end;
The as and is operators also work on interfaces (both COM and CORBA). They can be used to
check whether an interface also implements another interface as in the following example:
{$mode objfpc}
uses
SysUtils;
type
IMyInterface1 = interface
[’{DD70E7BB-51E8-45C3-8CE8-5F5188E19255}’]
procedure Bar;
end;
IMyInterface2 = interface
[’{7E5B86C4-4BC5-40E6-A0DF-D27DBF77BCA0}’]
procedure Foo;
end;
168
CHAPTER 12. EXPRESSIONS
procedure TMyObject.Bar;
begin
end;
procedure TMyObject.Foo;
begin
end;
var
i: IMyInterface1;
begin
i := TMyObject.Create;
i.Bar;
Writeln(BoolToStr(i is IMyInterface2, True)); // prints true
Writeln(BoolToStr(i is IDispatch, True)); // prints false
(i as IMyInterface2).Foo;
end.
Additionally, the is operator can be used to check if a class implements an interface, and the varas
operator can be used to typecast an interface back to the class:
{$mode objfpc}
var
i: IMyInterface;
begin
i := TMyObject.Create;
Writeln(BoolToStr(i is TMyObject,True)); // prints true
Writeln(BoolToStr(i is TObject,True)); // prints true
Writeln(BoolToStr(i is TAggregatedObject,True)); // prints false
(i as TMyObject).Foo;
end.
Although the interfaces must be COM interfaces, the typecast back to a class will only work if the
interface comes from an Object Pascal class. It will not work on interfaces obtained from the system
by COM.
169
Chapter 13
Statements
The heart of each algorithm are the actions it takes. These actions are contained in the statements of
a program or unit. Each statement can be labeled and jumped to (within certain limits) with Goto
statements. This can be seen in the following syntax diagram:
Statements
-
- statement -
label : simple statement
structured statement
asm statement
Simple statements
-
- simple statement assignment statement -
procedure statement
goto statement
raise statement
Of these statements, the raise statement will be explained in the chapter on Exceptions (chapter 17,
page 234)
13.1.1 Assignments
Assignments give a value to a variable, replacing any previous value the variable might have had:
170
CHAPTER 13. STATEMENTS
Assignments
-
- assignment statement variable reference := expression -
function identifier +=
-=
*=
/=
In addition to the standard Pascal assignment operator (:=), which simply replaces the value of the
variable with the value resulting from the expression on the right of the := operator, Free Pascal
supports some C-style constructions. All available constructs are listed in table (13.1).
For these constructs to work, the -Sc command-line switch must be specified.
Remark: These constructions are just for typing convenience, they don’t generate different code. Here are
some examples of valid assignment statements:
X := X+Y;
X+=Y; { Same as X := X+Y, needs -Sc command line switch}
X/=2; { Same as X := X/2, needs -Sc command line switch}
Done := False;
Weather := Good;
MyPi := 4* Tan(1);
Keeping in mind that the dereferencing of a typed pointer results in a variable of the type the pointer
points to, the following are also valid assignments:
Var
L : ^Longint;
P : PPChar;
begin
L^:=3;
P^^:=’A’;
171
CHAPTER 13. STATEMENTS
Procedure statements
-
- procedure statement procedure identifier -
method identifier actual parameter list
qualified method identifier
variable reference
The Free Pascal compiler will look for a procedure with the same name as given in the procedure
statement, and with a declared parameter list that matches the actual parameter list. The following
are valid procedure statements:
Usage;
WriteLn(’Pascal is an easy language !’);
Doit();
Remark: When looking for a function that matches the parameter list of the call, the parameter types should
be assignment-compatible for value and const parameters, and should match exactly for parameters
that are passed by reference.
Goto statement
-
- goto statement goto label -
1. The jump label must be defined in the same block as the Goto statement.
2. Jumping from outside a loop to the inside of a loop or vice versa can have strange effects.
3. To be able to use the Goto statement, the -Sg compiler switch must be used, or {$GOTO
ON} must be used.
Remark: In iso or macpas mode, or with the modeswitch "nonlocalgoto", the compiler will also allow non-
local gotos.
Goto statements are considered bad practice and should be avoided as much as possible. It is always
possible to replace a goto statement by a construction that doesn’t need a goto, although this
construction may not be as clear as a goto statement. For instance, the following is an allowed goto
statement:
172
CHAPTER 13. STATEMENTS
label
jumpto;
...
Jumpto :
Statement;
...
Goto jumpto;
...
Structured statements
-
- structured statement compound statement -
conditional statement
repetitive statement
with statement
exception statement
Conditional statements
-
- conditional statement case statement -
if statement
Repetitive statements
-
- repetitive statement for statament -
repeat statement
while statement
173
CHAPTER 13. STATEMENTS
Compound statements
-
- compound statement begin statement end -
6 ;
Case statement
-
- case statement case expression of case end -
6; else part ;
-
- case constant : statement -
6 .. constant
,
-
- else part else statementlist -
otherwise
The constants appearing in the various case parts must be known at compile-time, and can be of
the following types : enumeration types, Ordinal types (including chars) or string types. The case
expression must be also of this type, or a compiler error will occur. All case constants must have the
same type.
The compiler will evaluate the case expression. If one of the case constants’ value matches the
value of the expression, the statement that follows this constant is executed. After that, the program
continues after the final end.
If none of the case constants match the expression value, the statement list after the else or
otherwise keyword is executed. This can be an empty statement list. If no else part is present,
and no case constant matches the expression value, program flow continues after the final end.
The case statements can be compound statements (i.e. a Begin..End block).
Remark: Contrary to Turbo Pascal, duplicate case labels are not allowed in Free Pascal, so the following code
will generate an error when compiling:
Var i : integer;
...
Case i of
3 : DoSomething;
1..5 : DoSomethingElse;
end;
The compiler will generate a Duplicate case label error when compiling this, because the 3
also appears (implicitly) in the range 1..5. This is similar to Delphi syntax.
The following are valid case statements:
174
CHAPTER 13. STATEMENTS
Case C of
’a’ : WriteLn (’A pressed’);
’b’ : WriteLn (’B pressed’);
’c’ : WriteLn (’C pressed’);
else
WriteLn (’unknown letter pressed : ’,C);
end;
Or
Case C of
’a’,’e’,’i’,’o’,’u’ : WriteLn (’vowel pressed’);
’y’ : WriteLn (’This one depends on the language’);
else
WriteLn (’Consonant pressed’);
end;
Case Number of
1..10 : WriteLn (’Small number’);
11..100 : WriteLn (’Normal, medium number’);
else
WriteLn (’HUGE number’);
end;
Free Pascal allows the use of strings as case labels, and in that case the case variable must also
be a string. When using string types, the case variable and the various labels are compared in a
case-sensitive way.
Case lowercase(OS) of
’windows’,
’dos’ : WriteLn (’Microsoft playtform);
’macos’,
’darwin’ : Writeln(’Apple platform’);
’linux’,
’freebsd’,
’netbsd’ : Writeln(’Community platform’);
else
WriteLn (’Other platform’);
end;
The case with strings is equivalent to a series of if then else statements, no optimizations are
performed.
However, ranges are allowed, and are the equivalent of an
If then statements
175
CHAPTER 13. STATEMENTS
-
- if statement if expression then statement -
else statement
The expression between the if and then keywords must have a Boolean result type. If the
expression evaluates to True then the statement following the then keyword is executed.
If the expression evaluates to False, then the statement following the else keyword is executed,
if it is present.
Some points to note:
• Be aware of the fact that the boolean expression by default will be short-cut evaluated, meaning
that the evaluation will be stopped at the point where the outcome is known with certainty.
• Also, before the else keyword, no semicolon (;) is allowed, but all statements can be com-
pound statements.
• In nested If.. then .. else constructs, some ambiguity may araise as to which
else statement pairs with which if statement. The rule is that the else keyword matches
the first if keyword (searching backwards) not already matched by an else keyword.
For example:
If exp1 Then
If exp2 then
Stat1
else
stat2;
If exp1 Then
begin
If exp2 then
Stat1
else
stat2
end;
and not to
{ NOT EQUIVALENT }
If exp1 Then
begin
If exp2 then
Stat1
end
else
stat2;
If it is this latter construct which is needed, the begin and end keywords must be present. When in
doubt, it is better to add them.
The following is a valid statement:
176
CHAPTER 13. STATEMENTS
For statement
-
- for statement for control variable := initial value to -
downto
- final value do statement -
-
- control variable variable identifier -
-
- initial value expression -
-
- final value expression -
Here, Statement can be a compound statement. When the For statement is encountered, the
control variable is initialized with the initial value, and is compared with the final value. What
happens next depends on whether to or downto is used:
1. In the case To is used, if the initial value is larger than the final value then Statement will
never be executed.
2. In the case DownTo is used, if the initial value is less than the final value then Statement
will never be executed.
After this check, the statement after Do is executed. After the execution of the statement, the control
variable is increased or decreased with 1, depending on whether To or Downto is used. The control
variable must be an ordinal type, no other types can be used as counters in a loop.
Remark:
• Free Pascal always calculates the upper bound before initializing the counter variable with the
initial value.
• It is not allowed to change (i.e. assign a value to) the value of a loop variable inside the loop.
• The value of the loop variable is undefined after a loop has completed or if a loop is not exe-
cuted at all. If the loop was terminated prematurely with an exception or a break statement,
the loop variable retains the value it had when the loop was exited.
177
CHAPTER 13. STATEMENTS
For statement
-
- for in statement for control variable in enumerable do statement -
-
- control variable variable identifier -
-
- enumerable enumerated type -
expression
Here, Statement can be a compound statement. The enumerable must be an expression that
consists of a fixed number of elements: the loop variable will be made equal to each of the elements
in turn and the statement following the do keyword will be executed.
The enumerable expression can be one of 5 cases:
1. An enumeration type identifier. The loop will then be over all elements of the enumeration
type. The control variable must be of the enumeration type.
2. A set value. The loop will then be over all elements in the set, the control variable must be of
the base type of the set.
3. An array value. The loop will be over all elements in the array, and the control variable must
have the same type as an element in the array. As a special case, a string is regarded as an array
of characters.
4. An enumeratable class instance. This is an instance of a class that supports the IEnumerator
and IEnumerable interfaces. In this case, the control variable’s type must equal the type of
the IEnumerator.GetCurrent return value.
5. Any type for which an enumerator operator is defined. The enumerator operator must
return a class that implements the IEnumerator interface. The type of the control variable’s
type must equal the type of the enumerator class GetCurrent return value type.
178
CHAPTER 13. STATEMENTS
Type
TWeekDay = (monday, tuesday, wednesday, thursday,
friday,saturday,sunday);
Var
d : TWeekday;
begin
for d in TWeekday do
writeln(d);
end.
Type
TWeekDay = (monday, tuesday, wednesday, thursday,
friday,saturday,sunday);
Var
d : TWeekday;
begin
for d:=Low(TWeekday) to High(TWeekday) do
writeln(d);
end.
A second case of for..in loop is when the enumerable expression is a set, and then the loop will
be executed once for each element in the set:
Type
TWeekDay = (monday, tuesday, wednesday, thursday,
friday,saturday,sunday);
Var
Week : set of TWeekDay
= [monday, tuesday, wednesday, thursday, friday];
d : TWeekday;
begin
for d in Week do
writeln(d);
end.
This will print the names of the week days to the screen. Note that the variable d is of the same type
as the base type of the set.
The above for..in construct is equivalent to the following for..to construct:
Type
TWeekDay = (monday, tuesday, wednesday, thursday,
friday,saturday,sunday);
Var
179
CHAPTER 13. STATEMENTS
d : TWeekday;
begin
for d:=Low(TWeekday) to High(TWeekday) do
if d in Week then
writeln(d);
end.
The third possibility for a for..in loop is when the enumerable expression is an array:
var
a : Array[1..7] of string
= (’monday’,’tuesday’,’wednesday’,’thursday’,
’friday’,’saturday’,’sunday’);
Var
S : String;
begin
For s in a do
Writeln(s);
end.
This will also print all days in the week, and is equivalent to
var
a : Array[1..7] of string
= (’monday’,’tuesday’,’wednesday’,’thursday’,
’friday’,’saturday’,’sunday’);
Var
i : integer;
begin
for i:=Low(a) to high(a) do
Writeln(a[i]);
end.
A string type is equivalent to an array of char, and therefor a string can be used in a
for..in loop. The following will print all letters in the alphabet, each letter on a line:
Var
c : char;
begin
for c in ’abcdefghijklmnopqrstuvwxyz’ do
writeln(c);
end.
The fourth possibility for a for..in loop is using classes. A class can implement the IEnumerable
interface, which is defined as follows:
180
CHAPTER 13. STATEMENTS
IEnumerable = interface(IInterface)
function GetEnumerator: IEnumerator;
end;
The actual return type of the GetEnumerator must not necessarily be an IEnumerator inter-
face, instead, it can be a class which implements the methods of IEnumerator:
IEnumerator = interface(IInterface)
function GetCurrent: TObject;
function MoveNext: Boolean;
procedure Reset;
property Current: TObject read GetCurrent;
end;
The Current property and the MoveNext method must be present in the class returned by the
GetEnumerator method. The actual type of the Current property need not be a TObject.
When encountering a for..in loop with a class instance as the ’in’ operand, the compiler will
check each of the following conditions:
• Whether the result of GetEnumerator is a class with the following read-only property:
The type of the property must match the type of the control variable of the for..in loop.
Neither the IEnumerator nor the IEnumerable interfaces must actually be declared by the enu-
merable class: the compiler will detect whether these interfaces are present using the above checks.
The interfaces are only defined for Delphi compatibility and are not used internally. (it would also
be impossible to enforce their correctness).
The Classes unit contains a number of classes that are enumerable:
Thus, the following code will also print all days in the week:
{$mode objfpc}
uses classes;
Var
Days : TStrings;
D : String;
181
CHAPTER 13. STATEMENTS
begin
Days:=TStringList.Create;
try
Days.Add(’Monday’);
Days.Add(’Tuesday’);
Days.Add(’Wednesday’);
Days.Add(’Thursday’);
Days.Add(’Friday’);
Days.Add(’Saturday’);
Days.Add(’Sunday’);
For D in Days do
Writeln(D);
Finally
Days.Free;
end;
end.
Note that the compiler enforces type safety: declaring D as an integer will result in a compiler error:
{$mode objfpc}
uses classes;
Var
Days : TStrings;
D : String;
E : TStringsEnumerator;
begin
Days:=TStringList.Create;
try
Days.Add(’Monday’);
Days.Add(’Tuesday’);
Days.Add(’Wednesday’);
Days.Add(’Thursday’);
Days.Add(’Friday’);
Days.Add(’Saturday’);
Days.Add(’Sunday’);
E:=Days.getEnumerator;
try
While E.MoveNext do
begin
D:=E.Current;
Writeln(D);
end;
Finally
E.Free;
end;
Finally
Days.Free;
end;
end.
182
CHAPTER 13. STATEMENTS
Type
TEvenEnumerator = Class
FCurrent : Integer;
FMax : Integer;
Function MoveNext : Boolean;
Property Current : Integer Read FCurrent;
end;
begin
FCurrent:=FCurrent+2;
Result:=FCurrent<=FMax;
end;
begin
Result:=TEvenEnumerator.Create;
Result.FMax:=i;
end;
var
I : Integer;
m : Integer = 4;
begin
For I in M do
Writeln(i);
end.
The loop will print all nonzero even numbers smaller or equal to the enumerable. (2 and 4 in the case
of the example).
Care must be taken when defining enumerator operators: the compiler will find and use the first
available enumerator operator for the enumerable expression. For classes this also means that the
GetEnumerator method is not even considered. The following code will define an enumerator
operator which extracts the object from a stringlist:
{$mode objfpc}
uses classes;
Type
TDayObject = Class
DayOfWeek : Integer;
Constructor Create(ADayOfWeek : Integer);
183
CHAPTER 13. STATEMENTS
end;
TObjectEnumerator = Class
FList : TStrings;
FIndex : Integer;
Function GetCurrent : TDayObject;
Function MoveNext: boolean;
Property Current : TDayObject Read GetCurrent;
end;
begin
DayOfWeek:=ADayOfWeek;
end;
begin
Inc(FIndex);
Result:=(FIndex<FList.Count);
end;
begin
Result:=TObjectEnumerator.Create;
Result.Flist:=S;
Result.FIndex:=-1;
end;
Var
Days : TStrings;
D : String;
O : TdayObject;
begin
Days:=TStringList.Create;
try
Days.AddObject(’Monday’,TDayObject.Create(1));
Days.AddObject(’Tuesday’,TDayObject.Create(2));
Days.AddObject(’Wednesday’,TDayObject.Create(3));
Days.AddObject(’Thursday’,TDayObject.Create(4));
Days.AddObject(’Friday’,TDayObject.Create(5));
Days.AddObject(’Saturday’,TDayObject.Create(6));
Days.AddObject(’Sunday’,TDayObject.Create(7));
For O in Days do
Writeln(O.DayOfWeek);
Finally
184
CHAPTER 13. STATEMENTS
Days.Free;
end;
end.
The above code will print the day of the week for each day in the week.
If a class is not enumerable, the compiler will report an error when it is encountered in a for...in
loop.
Remark: Like the for..to loop, it is not allowed to change (i.e. assign a value to) the value of a loop control
variable inside the loop.
Repeat statement
-
- repeat statement repeat statement until expression -
6 ;
This will execute the statements between repeat and until up to the moment when Expression
evaluates to True. Since the expression is evaluated after the execution of the statements, they
are executed at least once.
Be aware of the fact that the boolean expression Expression will be short-cut evaluated by default,
meaning that the evaluation will be stopped at the point where the outcome is known with certainty.
The following are valid repeat statements
repeat
WriteLn (’I =’,i);
I := I+2;
until I>100;
repeat
X := X/2
until x<10e-3;
Note that the last statement before the until keyword does not need a terminating semicolon, but
it is allowed.
The Break and Continue system routines can be used to jump to the end or just after the end of
the repeat .. until statement. Note that Break and Continue are not reserved words and
therefor can be overloaded.
185
CHAPTER 13. STATEMENTS
While statements
-
- while statement while expression do statement -
This will execute Statement as long as Expression evaluates toTrue. Since Expression is
evaluated before the execution of Statement, it is possible that Statement isn’t executed at all.
Statement can be a compound statement.
Be aware of the fact that the boolean expression Expression will be short-cut evaluated by default,
meaning that the evaluation will be stopped at the point where the outcome is known with certainty.
The following are valid while statements:
I := I+2;
while i<=100 do
begin
WriteLn (’I =’,i);
I := I+2;
end;
X := X/2;
while x>=10e-3 do
X := X/2;
With statement
-
- with statement variable reference do statement -
6 ,
The variable reference must be a variable of a record, object or class type. In the with statement,
any variable reference, or method reference is checked to see if it is a field or method of the record
or object or class. If so, then that field is accessed, or that method is called. Given the declaration:
Type
Passenger = Record
Name : String[30];
Flight : String[10];
end;
Var
TheCustomer : Passenger;
186
CHAPTER 13. STATEMENTS
TheCustomer.Name := ’Michael’;
TheCustomer.Flight := ’PS901’;
and
With TheCustomer do
begin
Name := ’Michael’;
Flight := ’PS901’;
end;
The statement
is equivalent to
With A do
With B do
With C do
With D do Statement;
This also is a clear example of the fact that the variables are tried last to first, i.e., when the compiler
encounters a variable reference, it will first check if it is a field or method of the last variable. If not,
then it will check the last-but-one, and so on. The following example shows this;
Program testw;
Type AR = record
X,Y : Longint;
end;
PAR = ^Ar;
2 2
Showing thus that the X,Y in the WriteLn statement match the T record variable.
Remark: When using a With statement with a pointer, or a class, it is not permitted to change the pointer or
the class in the With block. With the definitions of the previous example, the following illustrates
what it is about:
Var p : PAR;
begin
187
CHAPTER 13. STATEMENTS
With P^ do
begin
// Do some operations
P:=OtherP;
X:=0.0; // Wrong X will be used !!
end;
The reason the pointer cannot be changed is that the address is stored by the compiler in a temporary
register. Changing the pointer won’t change the temporary address. The same is true for classes.
Assembler statements
-
- asm statement asm assembler code end -
registerlist
-
- registerlist [ stringconstant ] -
6 ,
More information about assembler blocks can be found in the Programmer’s Guide. The register list
is used to indicate the registers that are modified by an assembler statement in the assembler block.
The compiler stores certain results in the registers. If the registers are modified in an assembler
statement, the compiler should, sometimes, be told about it. The registers are denoted with their
Intel names for the I386 processor, i.e., ’EAX’, ’ESI’ etc... As an example, consider the following
assembler code:
asm
Movl $1,%ebx
Movl $0,%eax
addl %eax,%ebx
end [’EAX’,’EBX’];
This will tell the compiler that it should save and restore the contents of the EAX and EBX registers
when it encounters this asm statement.
Free Pascal supports various styles of assembler syntax. By default, AT&T syntax is assumed for the
80386 and compatibles platform. The default assembler style can be changed with the {$asmmode
xxx} switch in the code, or the -R command-line option. More about this can be found in the
Programmer’s Guide.
188
Chapter 14
• Function overloading, i.e. functions with the same name but different parameter lists.
• Const parameters.
Remark: In many of the subsequent paragraphs the words procedure and function will be used inter-
changeably. The statements made are valid for both, except when indicated otherwise.
Procedure declaration
-
- procedure declaration procedure header ; subroutine block ; -
-
- procedure header procedure identifier -
qualified method identifier
- formal parameter list hintdirectives -
modifiers
-
- subroutine block block -
external directive
asm block
forward
See section 14.4, page 191 for the list of parameters. A procedure declaration that is followed by a
block implements the action of the procedure in that block. The following is a valid procedure :
189
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
Function declaration
-
- function declaration function header ; subroutine block ; -
-
- function header function identifier -
qualified method identifier
- formal parameter list : result type hintdirectives -
modifiers
-
- subroutine block block -
external directive
asm block
forward
The result type of a function can be any previously declared type. contrary to Turbo Pascal, where
only simple types could be returned.
begin
MyFunction:=12; // Return 12
end;
begin
Result:=12;
end;
190
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
As an extension to Delphi syntax, the ObjFPC mode also supports a special extension of the Exit
procedure:
begin
Exit(12);
end;
The Exit call sets the result of the function and jumps to the final End of the function declaration
block. It can be seen as the equivalent of the C return instruction.
Remark: Function results are treated as pass-by-reference parameters. That is especially important for man-
aged types: The function result may be non-nil on entry, and set to a valid instance of the type.
Parameters
-
- formal parameter list ( parameter declaration ) -
6 ;
-
- parameter declaration value parameter -
variable parameter
out parameter
constant parameter
out parameter
Constant parameters, out parameters and variable parameters can also be untyped parameters if
they have no type identifier.
As of version 1.1, Free Pascal supports default values for both constant parameters and value pa-
rameters, but only for simple types. The compiler must be in OBJFPC or DELPHI mode to accept
default values.
Value parameters
- value parameter
- identifier list : parameter type -
array of
identifier : type identifier = default parameter value
191
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
When parameters are declared as value parameters, the procedure gets a copy of the parameters
that the calling statement passes. Any modifications to these parameters are purely local to the
procedure’s block, and do not propagate back to the calling block.
A block that wishes to call a procedure with value parameters must pass assignment compatible
parameters to the procedure. This means that the types should not match exactly, but can be converted
to the actual parameter types. This conversion code is inserted by the compiler itself.
Care must be taken when using value parameters: value parameters makes heavy use of the stack,
especially when using large parameters. The total size of all parameters in the formal parameter list
should be below 32K for portability’s sake (the Intel version limits this to 64K).
Open arrays can be passed as value parameters. See section 14.4.5, page 195 for more information
on using open arrays.
For a parameter of a simple type (i.e. not a structured type), a default value can be specified. This can
be an untyped constant. If the function call omits the parameter, the default value will be passed on
to the function. For dynamic arrays or other types that can be considered as equivalent to a pointer,
the only possible default value is Nil.
The following example will print 20 on the screen:
program testp;
Const
MyConst = 20;
begin
Writeln(’Function received : ’,I);
end;
begin
MyRealFunc;
end.
Variable parameters
-
- variable parameter var identifier list -
: type identifier
array of
When parameters are declared as variable parameters, the procedure or function accesses immedi-
ately the variable that the calling block passed in its parameter list. The procedure gets a pointer to
the variable that was passed, and uses this pointer to access the variable’s value. From this, it follows
that any changes made to the parameter, will propagate back to the calling block. This mechanism
can be used to pass values back in procedures. Because of this, the calling block must pass a pa-
rameter of exactly the same type as the declared parameter’s type. If it does not, the compiler will
generate an error.
192
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
Variable and constant parameters can be untyped. In that case the variable has no type, and hence is
incompatible with all other types. However, the address operator can be used on it, or it can be passed
to a function that has also an untyped parameter. If an untyped parameter is used in an assignment,
or a value must be assigned to it, a typecast must be used.
File type variables must always be passed as variable parameters.
Open arrays can be passed as variable parameters. See section 14.4.5, page 195 for more information
on using open arrays.
Remark:
• Note that default values are not supported for variable parameters. This would make little sense
since it defeats the purpose of being able to pass a value back to the caller.
• A function result is internally treated as a variable parameter, and may have a non-zero (or
non-nil) initial value. This is especially important for managed types.
Out parameters
-
- out parameter out identifier list -
: type identifier
array of
The purpose of an out parameter is to pass values back to the calling routine: the variable is passed
by reference. The initial value of the parameter on function entry is discarded, and should not be
used.
If a variable must be used to pass a value to a function and retrieve data from the function, then a
variable parameter must be used. If only a value must be retrieved, a out parameter can be used.
Needless to say, default values are not supported for out parameters.
The difference of out parameters and parameters by reference is very small (however, see below
for managed types): the former gives the compiler more information about what happens to the
arguments when passed to the procedure: it knows that the variable does not have to be initialized
prior to the call. The following example illustrates this:
begin
A:=2;
Writeln(’A is ’,A);
end;
begin
B:=2;
Writeln(’B is ’,B);
end;
193
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
Var
C,D : Integer;
begin
DoA(C);
DoB(D);
end.
Both procedures DoA and DoB do practically the same. But DoB’s declaration gives more informa-
tion to the compiler, allowing it to detect that D does not have to initialized before DoB is called.
Since the parameter A in DoA can receive a value as well as return one, the compiler notices that C
was not initialized prior to the call to DoA:
This shows that it is better to use out parameters when the parameter is used only to return a value.
Remark: Out parameters are only supported in Delphi and ObjFPC mode. For the other modes, out is a
valid identifier.
Remark: For managed types (reference counted types), using Out parameters incurs some overhead: the
compiler must be sure that the value is correctly initialized (i.e. has a reference count of zero (0)).
This initialization is normally done by the caller.
Constant parameters
Specifying a parameter as Constant is giving the compiler a hint that the contents of the parameter
will not be changed by the called routine. This allows the compiler to perform optimizations which
it could not do otherwise, and also to perform certain checks on the code inside the routine: namely,
it can forbid assignments to the parameter. Furthermore a const parameter cannot be passed on to
another function that requires a variable parameter: the compiler can check this as well. The main
use for this is reducing the stack size, hence improving performance, and still retaining the semantics
of passing by value...
Remark: Contrary to Delphi, no assumptions should be made about how const parameters are passed to
the underlying routine. In particular, the assumption that parameters with large size are passed by
reference is not correct. For this the constref parameter type should be used, which is available
as of version 2.5.1 of the compiler.
An exception is the stdcall calling convention: for compatibility with COM standards, large const
parameters are passed by reference.
194
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
Remark: Note that specifying const is a contract between the programmer and the compiler. It is the
programmer who tells the compiler that the contents of the const parameter will not be changed
when the routine is executed, it is not the compiler who tells the programmer that the parameter will
not be changed.
This is particularly important and visible when using refcounted types. For such types, the (invisible)
incrementing and decrementing of any reference count is omitted when const is used. Doing so
often allows the compiler to omit invisible try/finally frames for these routines.
As a side effect, the following code will produce not the expected output:
Var
S : String = ’Something’;
begin
S:=’Something else’;
Writeln(T);
end;
begin
DoIt(S);
end.
Will write
Something else
would be equivalent to
Where N would be the actual size of the array that is passed to the function. N-1 can be calculated
as High(Row).
Specifically, if an empty array is passed, then High(Parameter) returns -1, while low(Parameter)
returns 0.
195
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
Open parameters can be passed by value, by reference or as a constant parameter. In the latter cases
the procedure receives a pointer to the actual array. In the former case, it receives a copy of the array.
In a function or procedure, open arrays can only be passed to functions which are also declared with
open arrays as parameters, not to functions or procedures which accept arrays of fixed length. The
following is an example of a function using an open array:
As of FPC 2.2, it is also possible to pass partial arrays to a function that accepts an open array. This
can be done by specifying the range of the array which should be passed to the open array.
Given the declaration
Var
A : Array[1..100];
the following call will compute and print the average of the 100 numbers:
But the following will compute and print the average of the first and second half:
Type
PVarRec = ^TVarRec;
TVarRec = record
case VType : Ptrint of
vtInteger : (VInteger: Longint);
vtBoolean : (VBoolean: Boolean);
vtChar : (VChar: Char);
vtWideChar : (VWideChar: WideChar);
vtExtended : (VExtended: PExtended);
vtString : (VString: PShortString);
196
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
Therefor, inside the procedure body, the array of const argument is equivalent to an open array
of TVarRec:
Var I : longint;
begin
If High(Args)<0 then
begin
Writeln (’No aguments’);
exit;
end;
Writeln (’Got ’,High(Args)+1,’ arguments :’);
For i:=0 to High(Args) do
begin
write (’Argument ’,i,’ has type ’);
case Args[i].vtype of
vtinteger :
Writeln (’Integer, Value :’,args[i].vinteger);
vtboolean :
Writeln (’Boolean, Value :’,args[i].vboolean);
vtchar :
Writeln (’Char, value : ’,args[i].vchar);
vtextended :
Writeln (’Extended, value : ’,args[i].VExtended^);
vtString :
Writeln (’ShortString, value :’,args[i].VString^);
vtPointer :
Writeln (’Pointer, value : ’,Longint(Args[i].VPointer));
vtPChar :
Writeln (’PChar, value : ’,Args[i].VPChar);
vtObject :
Writeln (’Object, name : ’,Args[i].VObject.Classname);
vtClass :
Writeln (’Class reference, name :’,Args[i].VClass.Classname);
vtAnsiString :
Writeln (’AnsiString, value :’,AnsiString(Args[I].VAnsiString);
else
Writeln (’(Unknown) : ’,args[i].vtype);
197
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
end;
end;
end;
S:=’Ansistring 1’;
T:=’AnsiString 2’;
Testit ([]);
Testit ([1,2]);
Testit ([’A’,’B’]);
Testit ([TRUE,FALSE,TRUE]);
Testit ([’String’,’Another string’]);
Testit ([S,T]) ;
Testit ([P1,P2]);
Testit ([@testit,Nil]);
Testit ([ObjA,ObjB]);
Testit ([1.234,1.234]);
TestIt ([AClass]);
If the procedure is declared with the cdecl modifier, then the compiler will pass the array as a C
compiler would pass it. This, in effect, emulates the C construct of a variable number of arguments,
as the following example will show:
program testaocc;
{$mode objfpc}
Const
P : PChar = ’example’;
Fmt : PChar =
’This %s uses printf to print numbers (%d) and strings.’#10;
begin
printf(Fmt,[P,123]);
end.
Remark that this is not true for Delphi, so code relying on this feature will not be portable.
Remark: Note that there is no support for QWord arguments in array of const. This is for Delphi
compatibility, and the compiler will ignore any resulting range checks when in mode Delphi.
• nothing (pass by value): the reference count of the parameter is increased on entry and de-
creased on exit.
198
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
• out: the reference count of the value that is passed in is decreased by 1, and the variable that’s
passed into the procedure is initialized to "empty" (usually Nil, but that is an implementation
detail which should not be relied on).
• var nothing happens to the reference count. A reference to the original variable is passed
in, and changing it or reading it has exactly the same effect as changing/reading the original
variable.
• const this case is slightly tricky. Nothing happens to the reference count because you can
pass non-lvalues here. In particular, you can pass a class implementing an interface rather than
the interface itself which can cause the class to be freed unexpectedly.
Remark: The function result is internally treated as a var parameter to the function, and the same rules as for
var parameters apply.
The following example demonstrates the dangers:
{$mode objfpc}
Type
ITest = Interface
Procedure DoTest(ACount : Integer);
end;
TTest = Class(TInterfacedObject,ITest)
Procedure DoTest(ACount : Integer);
Destructor destroy; override;
end;
Destructor TTest.Destroy;
begin
Writeln(’Destroy called’);
end;
begin
Writeln(’Test ’,ACount,’ : ref count: ’,RefCount);
end;
begin
// Reference count is increased
x.DoTest(ACount);
// And decreased
end;
begin
// No change to reference count.
x.DoTest(ACount);
end;
199
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
Procedure Test1;
var
y: ITest;
begin
y := TTest.Create;
// Ref. count is 1 at this point.
y.DoTest(1);
// Calling DoIT will increase reference count and decrease on exit.
DoIt1(y,2);
// Reference count is still one.
y.DoTest(3);
end;
Procedure Test2;
var
Y : TTest;
begin
Y := TTest.Create; // no count on the object yet
// Ref. count is 0 at this point.
y.DoTest(3);
// Ref count will remain zero.
DoIt2(y,4);
Y.DoTest(5);
Y.Free;
end;
Procedure Test3;
var
Y : TTest;
begin
Y := TTest.Create; // no count on the object yet
// Ref. count is 0 at this point.
y.DoTest(6);
// Ref count will remain zero.
DoIt1(y,7);
y.DoTest(8);
end;
begin
Test1;
Test2;
Test3;
end.
200
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
Destroy called
Test 3 : ref count: 0
Test 4 : ref count: 0
Test 5 : ref count: 0
Destroy called
Test 6 : ref count: 0
Test 7 : ref count: 1
Destroy called
Test 8 : ref count: 0
As can be seen, in test3, the reference count is decreased from 1 to 0 at the end of the DoIt call,
causing the instance to be freed before the call returns.
The following small program demonstrates the reference counts used in strings:
{$mode objfpc}
{$H+}
Type
PAnsiRec = ^TAnsiRec;
TAnsiRec = Record
CodePage : TSystemCodePage;
ElementSize : Word;
{$ifdef CPU64}
{ align fields }
Dummy : DWord;
{$endif CPU64}
Ref : SizeInt;
Len : SizeInt;
end;
begin
if P=Nil then
Result:=0
else
Result:=PAnsiRec(P-SizeOf(TAnsiRec))^.Ref;
end;
begin
Writeln(’By var, ref count : ’,SRefCount(Pointer(S)));
end;
begin
Writeln(’Const, ref count : ’,SRefCount(Pointer(S)));
end;
201
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
begin
Writeln(’Value, ref count : ’,SRefCount(Pointer(S)));
end;
begin
Writeln(’Function argument, ref count : ’,SRefCount(Pointer(S)));
Writeln(’Function result, ref count : ’,SRefCount(Pointer(Result)));
end;
Var
S,T : String;
begin
S:=’Some string’;
Writeln(’Constant : ’,SrefCount(Pointer(S)));
UniqueString(S);
Writeln(’Unique : ’,SRefCount(Pointer(S)));
T:=S;
Writeln(’After Assign : ’,SRefCount(Pointer(S)));
ByVar(S);
ByConst(S);
ByVal(S);
UniqueString(S);
T:=FunctionResult(S);
Writeln(’After function : ’,SRefCount(Pointer(S)));
end.
...
Dec(Var I : Longint;decrement : Longint);
Dec(Var I : Longint);
Dec(Var I : Byte;decrement : Longint);
Dec(Var I : Byte);
...
When the compiler encounters a call to the Dec function, it will first search which function it should
use. It therefore checks the parameters in a function call, and looks if there is a function definition
which matches the specified parameter list. If the compiler finds such a function, a call is inserted to
that function. If no such function is found, a compiler error is generated.
Functions that have a cdecl modifier cannot be overloaded. (Technically, because this modifier
prevents the mangling of the function name by the compiler).
Prior to version 1.9 of the compiler, the overloaded functions needed to be in the same unit. Now the
202
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
compiler will continue searching in other units if it doesn’t find a matching version of an overloaded
function in one unit, and if the overload keyword is present.
If the overload keyword is not present, then all overloaded versions must reside in the same unit,
and if it concerns methods part of a class, they must be in the same class, i.e. the compiler will not
look for overloaded methods in parent classes if the overload keyword was not specified.
Program testforward;
Procedure First (n : longint); forward;
Procedure Second;
begin
WriteLn (’In second. Calling first...’);
First (1);
end;
Procedure First (n : longint);
begin
WriteLn (’First received : ’,n);
end;
begin
Second;
end.
A function can be forward declared only once. Likewise, in units, it is not allowed to have a forward
declared function of a function that has been declared in the interface part. The interface declaration
counts as a forward declaration. The following unit will give an error when compiled:
Unit testforward;
interface
Procedure First (n : longint);
Procedure Second;
implementation
Procedure First (n : longint); forward;
Procedure Second;
begin
WriteLn (’In second. Calling first...’);
First (1);
end;
Procedure First (n : longint);
begin
WriteLn (’First received : ’,n);
end;
end.
Reversely, functions declared in the interface section cannot be declared forward in the implementa-
tion section. Logically, since they already have been declared.
203
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
External directive
program CmodDemo;
{$Linklib c}
Const P : PChar = ’This is fun !’;
Function strlen (P : PChar) : Longint; cdecl; external;
begin
WriteLn (’Length of (’,p,’) : ’,strlen(p))
end.
Remark: The parameters in the declaration of the external function should match exactly the ones in the
declaration in the object file.
If the external modifier is followed by a string constant:
external ’lname’;
Then this tells the compiler that the function resides in library ’lname’. The compiler will then
automatically link this library to the program.
The name that the function has in the library can also be specified:
This tells the compiler that the function resides in library ’lname’, but with name ’Fname’. The
compiler will then automatically link this library to the program, and use the correct name for the
function. Under W INDOWS and OS /2, the following form can also be used:
This tells the compiler that the function resides in library ’lname’, but with index Ind. The compiler
will then automatically link this library to the program, and use the correct index for the function.
Finally, the external directive can be used to specify the external name of the function :
This tells the compiler that the function has the name ’Fname’. The correct library or object file (in
this case myfunc.o) must still be linked, ensuring that the function ’Fname’ is indeed included in the
linking stage.
204
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
Assembler functions
-
- asm block assembler ; declaration part asm statement -
Contrary to Delphi, the assembler keyword must be present to indicate an assembler function. For
more information about assembler functions, see the chapter on using assembler in the Programmer’s
Guide.
14.10 Modifiers
A function or procedure declaration can contain modifiers. Here we list the various possibilities:
Modifiers
-
- modifiers ; public -
6 name string constant
export
alias : string constant
interrupt
iochecks
call modifiers
-
- call modifiers cdecl -
inline
local
nostackframe
overload
pascal
register
safecall
saveregisters
softfloat
stdcall
varargs
Free Pascal doesn’t support all Turbo Pascal modifiers (although it parses them for compatibility),
but does support a number of additional modifiers. They are used mainly for assembler and reference
to C object files.
205
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
14.10.1 alias
The alias modifier allows the programmer to specify a different name for a procedure or function.
This is mostly useful for referring to this procedure from assembly language constructs or from
another object file. As an example, consider the following program:
Program Aliases;
Remark: The specified alias is inserted straight into the assembly code, thus it is case sensitive.
The alias modifier does not make the symbol public to other modules, unless the routine is also
declared in the interface part of a unit, or the public modifier is used to force it as public. Consider
the following:
unit testalias;
interface
procedure testroutine;
implementation
procedure testroutine;alias:’ARoutine’;
begin
WriteLn(’Hello world’);
end;
end.
This will make the routine testroutine available publicly to external object files under the label
name ARoutine.
Remark: The alias directive is considered deprecated. Please use the public name directive. See section
14.10.12, page 210.
14.10.2 cdecl
The cdecl modifier can be used to declare a function that uses a C type calling convention. This
must be used when accessing functions residing in an object file generated by standard C compilers,
but must also be used for Pascal functions that are to be used as callbacks for C libraries.
The cdecl modifier allows to use C function in the code. For external C functions, the object file
containing the C implementation of the function or procedure must be linked in. As an example:
program CmodDemo;
206
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
{$LINKLIB c}
Const P : PChar = ’This is fun !’;
Function StrLen(P: PChar): Longint;cdecl; external name ’strlen’;
begin
WriteLn (’Length of (’,p,’) : ’,StrLen(p));
end.
When compiling this, and linking to the C-library, the strlen function can be called throughout the
program. The external directive tells the compiler that the function resides in an external object
file or library with the ’strlen’ name (see 14.8).
Remark: The parameters in our declaration of the C function should match exactly the ones in the declaration
in C.
For functions that are not external, but which are declared using cdecl, no external linking is
needed. These functions have some restrictions, for instance the array of const construct can
not be used (due the way this uses the stack). On the other hand, the cdecl modifier allows these
functions to be used as callbacks for routines written in C, as the latter expect the ’cdecl’ calling
convention.
14.10.3 export
The export modifier is used to export names when creating a shared library or an executable
program. This means that the symbol will be publicly available, and can be imported from other
programs. For more information on this modifier, consult the section on “Making libraries” in the
Programmer’s Guide.
14.10.4 inline
Procedures that are declared inline are copied to the places where they are called. This has the
effect that there is no actual procedure call, the code of the procedure is just copied to where the
procedure is needed, this results in faster execution speed if the function or procedure is used a lot.
It is obvious that inlining large functions does not make sense.
By default, inline procedures are not allowed. Inline code must be enabled using the command-
line switch -Si or {$inline on} directive.
Remark:
1. inline is only a hint for the compiler. This does not automatically mean that all calls are
inlined; sometimes the compiler may decide that a function simply cannot be inlined, or that a
particular call to the function cannot be inlined. If so, the compiler will emit a warning.
2. In old versions of Free Pascal, inline code was not exported from a unit. This meant that when
calling an inline procedure from another unit, a normal procedure call will be performed. Only
inside units, Inline procedures are really inlined. As of version 2.0.2, inline works accross
units.
3. Recursive inline functions are not allowed. i.e. an inline function that calls itself is not allowed.
14.10.5 interrupt
The interrupt keyword is used to declare a routine which will be used as an interrupt handler.
On entry to this routine, all the registers will be saved and on exit, all registers will be restored and
an interrupt or trap return will be executed (instead of the normal return from subroutine instruction).
207
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
On platforms where a return from interrupt does not exist, the normal exit code of routines will be
done instead. For more information on the generated code, consult the Programmer’s Guide.
14.10.6 iocheck
The iocheck keyword is used to declare a routine which causes generation of I/O result checking
code within a {$IOCHECKS ON} block whenever it is called.
The result is that if a call to this procedure is generated, the compiler will insert I/O checking code if
the call is within a {$IOCHECKS ON} block.
This modifier is intended for RTL internal routines, not for use in application code.
14.10.7 local
The local modifier allows the compiler to optimize the function: a local function cannot be in the
interface section of a unit: it is always in the implementation section of the unit. From this it follows
that the function cannot be exported from a library.
On Linux, the local directive results in some optimizations. On Windows, it has no effect. It was
introduced for Kylix compatibility.
14.10.8 noreturn
The noreturn modifier can be used to tell the compiler the procedure does not return. This infor-
mation can used by the compiler to avoid emitting warnings about uninitialized variables or results
not being set.
In the following example, the compiler will not emit a warning that the result may not be set in
function f:
procedure do_halt;noreturn;
begin
halt(1);
end;
begin
if (i<0) then
do_halt
else
result:=i;
end;
14.10.9 nostackframe
The nostackframe modifier can be used to tell the compiler it should not generate a stack frame
for this procedure or function. By default, a stack frame is always generated for each procedure or
function.
One should be extremely careful when using this modifier: most procedures or functions need a stack
frame. Particularly for debugging they are needed.
208
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
14.10.10 overload
The overload modifier tells the compiler that this function is overloaded. It is mainly for Delphi
compatibility, as in Free Pascal, all functions and procedures can be overloaded without this modifier.
There is only one case where the overload modifier is mandatory: if a function must be overloaded
that resides in another unit. Both functions must be declared with the overload modifier: the
overload modifier tells the compiler that it should continue looking for overloaded versions in
other units.
The following example illustrates this. Take the first unit:
unit ua;
interface
implementation
begin
Writeln(’ua.DoIt received ’,A)
end;
end.
unit ub;
interface
implementation
begin
Writeln(’ub.DoIt received ’,A)
end;
end.
program uab;
uses ua,ub;
begin
DoIt(’Some string’);
end.
209
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
When the compiler starts looking for the declaration of DoIt, it will find one in the ub unit. Without
the overload directive, the compiler would give an argument mismatch error:
With the overload directive in place at both locations, the compiler knows it must continue search-
ing for an overloaded version with matching parameter list. Note that both declarations must have
the overload modifier specified; it is not enough to have the modifier in unit ub. This is to prevent
unwanted overloading: the programmer who implemented the ua unit must mark the procedure as
fit for overloading.
14.10.11 pascal
The pascal modifier can be used to declare a function that uses the classic Pascal type calling
convention (passing parameters from left to right). For more information on the Pascal calling con-
vention, consult the Programmer’s Guide.
14.10.12 public
The Public keyword is used to declare a function globally in a unit. This is useful if the function
should not be accessible from the unit file (i.e. another unit/program using the unit doesn’t see the
function), but must be accessible from the object file. As an example:
Unit someunit;
interface
Function First : Real;
Implementation
Function First : Real;
begin
First := 0;
end;
Function Second : Real; [Public];
begin
Second := 1;
end;
end.
If another program or unit uses this unit, it will not be able to use the function Second, since it
isn’t declared in the interface part. However, it will be possible to access the function Second at the
assembly-language level, by using its mangled name (see the Programmer’s Guide).
The public modifier can also be followed by a name directive to specify the assembler name, as
follows:
Unit someunit;
interface
Function First : Real;
Implementation
Function First : Real;
begin
First := 0;
end;
210
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
The assembler symbol as specified by the ’public name’ directive will be ’second’, in all lowercase
letters.
14.10.13 register
The register keyword is used for compatibility with Delphi. In version 1.0.x of the compiler, this
directive has no effect on the generated code. As of the 1.9.X versions, this directive is supported.
The first three arguments are passed in registers EAX,ECX and EDX.
14.10.14 safecall
The safecall modifier ressembles closely the stdcall modifier. It sends parameters from right
to left on the stack. Additionally, the called procedure saves and restores all registers.
More information about this modifier can be found in the Programmer’s Guide, in the section on the
calling mechanism and the chapter on linking.
14.10.15 saveregisters
The saveregisters modifier tells the compiler that all CPU registers should be saved prior to
calling this routine. Which CPU registers are saved, depends entirely on the CPU.
14.10.16 softfloat
The softfloat modifier makes sense only on the ARM architecture.
14.10.17 stdcall
The stdcall modifier pushes the parameters from right to left on the stack, it also aligns all the
parameters to a default alignment.
More information about this modifier can be found in the Programmer’s Guide, in the section on the
calling mechanism and the chapter on linking.
14.10.18 varargs
This modifier can only be used together with the cdecl modifier, for external C procedures. It
indicates that the procedure accepts a variable number of arguments after the last declared variable.
These arguments are passed on without any type checking. It is equivalent to using the array of
const construction for cdecl procedures, without having to declare the array of const. The
square brackets around the variable arguments do not need to be used when this form of declaration
is used.
The following declarations are 2 ways of referring to the same function in the C library:
211
CHAPTER 14. USING FUNCTIONS AND PROCEDURES
PrintF1(’%d %d\n’,1,1);
PrintF2(’%d %d\n’,[1,1]);
The compiler will give a warning when it encounters these modifiers, but will otherwise completely
ignore them.
212
Chapter 15
Operator overloading
15.1 Introduction
Free Pascal supports operator overloading. This means that it is possible to define the action of some
operators on self-defined types, and thus allow the use of these types in mathematical expressions.
Defining the action of an operator is much like the definition of a function or procedure, only there
are some restrictions on the possible definitions, as will be shown in the subsequent.
Operator overloading is, in essence, a powerful notational tool; but it is also not more than that, since
the same results can be obtained with regular function calls. When using operator overloading, it is
important to keep in mind that some implicit rules may produce some unexpected results. This will
be indicated.
Operator definitions
-
- operator definition operator assignment operator definition -
arithmetic operator definition
comparision operator definition
- result identifier : result type ; subroutine block -
-
- assignment operator definition := ( value parameter ) -
explicit
-
- arithmetic operator definition + ( parameter list ) -
-
*
/
**
><
213
CHAPTER 15. OPERATOR OVERLOADING
-
- comparision operator definition = ( parameter list ) -
<
<=
>
>=
<>
in
The parameter list for a comparison operator or an arithmetic operator must always contain 2 param-
eters, with the exception of the unary minus, where only 1 parameters is needed. The result type of
the comparison operator must be Boolean.
Remark: When compiling in Delphi mode or Objfpc mode, the result identifier may be dropped. The
result can then be accessed through the standard Result symbol.
If the result identifier is dropped and the compiler is not in one of these modes, a syntax error will
occur.
The statement block contains the necessary statements to determine the result of the operation. It
can contain arbitrary large pieces of code; it is executed whenever the operation is encountered in
some expression. The result of the statement block must always be defined; error conditions are not
checked by the compiler, and the code must take care of all possible cases, throwing a run-time error
if some error condition is encountered.
In the following, the three types of operator definitions will be examined. As an example, throughout
this chapter the following type will be used to define overloaded operators on :
type
complex = record
re : real;
im : real;
end;
Var
C,Z : Complex; // New type complex
begin
Z:=C; // assignments between complex types.
end;
214
CHAPTER 15. OPERATOR OVERLOADING
var
R : real;
C : complex;
begin
C:=R;
end;
As can be seen from this statement, it defines the action of the operator := with at the right a real
expression, and at the left a complex expression.
An example implementation of this could be as follows:
begin
z.re:=r;
z.im:=0.0;
end;
As can be seen in the example, the result identifier (z in this case) is used to store the result of the
assignment. When compiling in Delphi mode or ObjFPC mode, the use of the special identifier
Result is also allowed, and can be substituted for the z, so the above would be equivalent to
begin
Result.re:=r;
Result.im:=0.0;
end;
The assignment operator is also used to convert types from one type to another. The compiler will
consider all overloaded assignment operators till it finds one that matches the types of the left hand
and right hand expressions. If no such operator is found, a ’type mismatch’ error is given.
Remark: The assignment operator is not commutative; the compiler will never reverse the role of the two
arguments. In other words, given the above definition of the assignment operator, the following is
not possible:
var
R : real;
C : complex;
begin
R:=C;
end;
215
CHAPTER 15. OPERATOR OVERLOADING
If the reverse assignment should be possible then the assignment operator must be defined for that as
well. (This is not so for reals and complex numbers.)
Remark: The assignment operator is also used in implicit type conversions. This can have unwanted effects.
Consider the following definitions:
Var
r1,r2 : real;
begin
r1:=exp(r2);
end;
The mismatch occurs because the compiler will encounter the definition of the exp function with
the complex argument. It implicitly converts r2 to a complex, so it can use the above exp function.
The result of this function is a complex, which cannot be assigned to r1, so the compiler will give
a ’type mismatch’ error. The compiler will not look further for another exp which has the correct
arguments.
It is possible to avoid this particular problem by specifying
r1:=system.exp(r2);
When doing an explicit typecast, the compiler will attempt an implicit conversion if an assignment
operator is present. That means that
Var
R1 : T1;
R2 : T2;
begin
R2:=T2(R1);
However, an Explicit operator can be defined, and then it will be used instead when the compiler
encounters a typecast.
The reverse is not true: In a regular assignment, the compiler will not consider explicit assignment
operators.
Given the following definitions:
uses
sysutils;
type
TTest1 = record
f: LongInt;
end;
216
CHAPTER 15. OPERATOR OVERLOADING
TTest2 = record
f: String;
end;
TTest3 = record
f: Boolean;
end;
var
t1: TTest1;
t2: TTest2;
t3: TTest3;
begin
t1.f := 42;
// Implicit
t2 := t1;
// theoretically explicit, but implicit op will be used,
// because no explicit operator is defined
t2 := TTest2(t1);
// the following would not compile,
// no assignment operator defined (explicit one won’t be used here)
//t1 := t2;
// Explicit
t1 := TTest1(t2);
// first explicit (TTest2 => TTest1) then implicit (TTest1 => TTest3)
217
CHAPTER 15. OPERATOR OVERLOADING
t3 := TTest1(t2);
// Implicit
t3 := t1;
// explicit
t3 := TTest3(t1);
end.
The definition of an arithmetic operator takes two parameters, except for unary minus, which needs
only 1 parameter. The first parameter must be of the type that occurs at the left of the operator, the
second parameter must be of the type that is at the right of the arithmetic operator. The result type
must match the type that results after the arithmetic operation.
To compile an expression as
var
R : real;
C,Z : complex;
begin
C:=R*Z;
end;
218
CHAPTER 15. OPERATOR OVERLOADING
begin
z.re := z1.re * r;
z.im := z1.im * r;
end;
As can be seen, the first operator is a real, and the second is a complex. The result type is complex.
Multiplication and addition of reals and complexes are commutative operations. The compiler, how-
ever, has no notion of this fact so even if a multiplication between a real and a complex is defined,
the compiler will not use that definition when it encounters a complex and a real (in that order). It is
necessary to define both operations.
So, given the above definition of the multiplication, the compiler will not accept the following state-
ment:
var
R : real;
C,Z : complex;
begin
C:=Z*R;
end;
Since the types of Z and R don’t match the types in the operator definition.
The reason for this behaviour is that it is possible that a multiplication is not always commutative.
E.g. the multiplication of a (n,m) with a (m,n) matrix will result in a (n,n) matrix, while the
multiplication of a (m,n) with a (n,m) matrix is a (m,m) matrix, which needn’t be the same in
all cases.
If there is no separate operator for unequal to (<>), then, to evaluate a statement that contains the
unequal to operator, the compiler uses the equal to operator (=), and negates the result. The opposite
is not true: if no "equal to" but an "unequal to" operator exists, the compiler will not use it to evaluate
an expression containing the equal (=) operator.
As an example, the following operator allows to compare two complex numbers:
219
CHAPTER 15. OPERATOR OVERLOADING
Var
C1,C2 : Complex;
begin
If C1=C2 then
Writeln(’C1 and C2 are equal’);
end;
The comparison operator definition needs 2 parameters, with the types that the operator is meant to
compare. Here also, the compiler doesn’t apply commutativity: if the two types are different, then it
is necessary to define 2 comparison operators.
In the case of complex numbers, it is, for instance necessary to define 2 comparisons: one with the
complex type first, and one with the real type first.
Given the definitions
Var
R,S : Real;
C : Complex;
begin
If (C=R) or (S=C) then
Writeln (’Ok’);
end;
Note that the order of the real and complex type in the two comparisons is reversed.
The following example shows that the result type does not need to be a boolean:
Type
TMyRec = record a,b : integer; end;
begin
if (x.a=y.a) and (x.b=y.b) then
R:=’equal’
else
R:=’differ’;
end;
var
x,y : TMyRec;
begin
x.a:=1;
220
CHAPTER 15. OPERATOR OVERLOADING
y.a:=1;
Writeln(x=y);
x.a:=2;
y.a:=3;
Writeln(x=y);
end.
equal
differ
obviously, a statement as
if (x=y) then
writeln(’Equal’);
15.6 In operator
As of version 2.6 of Free pascal, the In operator can be overloaded as well. The first argument of
the in operator must be the operand on the left of the in keyword. The following overloads the in
operator for records:
{$mode objfpc}{$H+}
type
TMyRec = record A: Integer end;
var
R: TMyRec;
begin
R.A := 10;
Writeln(1 in R); // false
Writeln(10 in R); // true
end.
The in operator can also be overloaded for other types than ordinal types, as in the following exam-
ple:
{$mode objfpc}{$H+}
type
TMyRec = record A: Integer end;
221
CHAPTER 15. OPERATOR OVERLOADING
var
S,R: TMyRec;
begin
R.A := 10;
S.A:=1;
Writeln(S in R); // false
Writeln(R in R); // true
end.
222
Chapter 16
A Pascal program can consist of modules called units. A unit can be used to group pieces of code
together, or to give someone code without giving the sources. Both programs and units consist of
code blocks, which are mixtures of statements, procedures, and variable or type declarations.
16.1 Programs
A Pascal program consists of the program header, followed possibly by a ’uses’ clause, and a block.
Programs
-
- program program header ; block . -
uses clause
-
- program header program identifier -
( program parameters )
-
- program parameters identifier list -
-
- uses clause uses identifier ; -
6 in string literal
,
The program header is provided for backwards compatibility, and is ignored by the compiler.
The uses clause serves to identify all units that are needed by the program. All identifiers which are
declared in the interface section of the units in the uses clause are added to the known identifiers of
the program. The system unit doesn’t have to be in this list, since it is always loaded by the compiler.
The order in which the units appear is significant, it determines in which order they are initialized.
Units are initialized in the same order as they appear in the uses clause. Identifiers are searched in the
opposite order, i.e. when the compiler searches for an identifier, then it looks first in the last unit in
the uses clause, then the last but one, and so on. This is important in case two units declare different
types with the same identifier.
The compiler will look for compiled versions or source versions of all units in the uses clause in the
unit search path. If the unit filename was explicitly mentioned using the in keyword, the source is
taken from the filename specified:
223
CHAPTER 16. PROGRAMS, UNITS, BLOCKS
program programb;
Additionally, If a unit name is longer than 8 characters, the compiler will first look for a unit name
with this length, and then it will truncate the name to 8 characters and look for it again. For compat-
ibility reasons, this is also true on platforms that support long file names.
Note that the above search is performed in each directory in the search path.
The program block contains the statements that will be executed when the program is started. Note
that these statements need not necessarily be the first statements that are executed: the initialization
code of the units may also contain statements that are executed prior to the program code.
The structure of a program block is discussed below.
16.2 Units
A unit contains a set of declarations, procedures and functions that can be used by a program or
another unit. The syntax for a unit is as follows:
Units
-
- unit unit header interface part implementation part -
- end . -
initialization part
finalization part
begin statement
6 ;
.
-
- unit header unit unit identifier
? ; -
hint directives
-
- interface part interface -
uses clause 6 constant declaration part
type declaration part
variable declaration part
property declaration part
procedure headers part
-
- procedure headers part procedure header ; -
function header call modifiers ;
224
CHAPTER 16. PROGRAMS, UNITS, BLOCKS
-
- implementation part implementation declaration part -
uses clause
-
- initialization part initialization statement -
6 ;
-
- finalization part finalization statement -
6 ;
As can be seen from the syntax diagram, a unit always consists of a interface and an implementation
part. Optionally, there is an initialization block and a finalization block, containing code that will be
executed when the program is started, and when the program stops, respectively.
Both the interface part or implementation part can be empty, but the keywords Interface and
implementation must be specified. The following is a completely valid unit;
unit a;
interface
implementation
end.
The interface part declares all identifiers that must be exported from the unit. This can be constant,
type or variable identifiers, and also procedure or function identifier declarations. The interface part
cannot contain code that is executed: only declarations are allowed. The following is a valid interface
part:
unit a;
interface
uses b;
Implementation
unit unita;
interface
implementation
end.
225
CHAPTER 16. PROGRAMS, UNITS, BLOCKS
The implementation part is primarily intended for the implementation of the functions and procedures
declared in the interface part. However, it can also contain declarations of it’s own: the declarations
inside the implementation part are not accessible outside the unit.
The initialization and finalization part of a unit are optional.
The initialization block is used to initialize certain variables or execute code that is necessary for the
correct functioning of the unit. The initialization parts of the units are executed in the order that the
compiler loaded the units when compiling a program. They are executed before the first statement of
the program is executed.
The finalization part of the units are executed in the reverse order of the initialization execution. They
are used for instance to clean up any resources allocated in the initialization part of the unit, or during
the lifetime of the program. The finalization part is always executed in the case of a normal program
termination: whether it is because the final end is reached in the program code or because a Halt
instruction was executed somewhere.
In case the program stops during the execution of the initialization blocks of one of the units, only
the units that were already initialized will be finalized. Note that in difference with Delphi, in Free
Pascal a finalization block can be present without an Initialization block. That means
the following will compile in Free Pascal, but not in Delphi.
Finalization
CleanupUnit;
end.
An initialization section by itself (i.e. without finalization) may simply be replaced by a statement
block. That is, the following:
Initialization
InitializeUnit;
end.
is completely equivalent to
Begin
InitializeUnit;
end.
unit a.b;
interface
Function C : integer;
226
CHAPTER 16. PROGRAMS, UNITS, BLOCKS
implementation
Function C : integer;
begin
Result:=1;
end;
end.
program d;
uses a.b;
begin
Writeln(c);
end.
When resolving symbols, unit scopes always take precedence over symbols inside units.
Given the following units:
unit myunit;
interface
var
test: record
a: longint;
end;
implementation
initialization
test.a:=2;
end.
and
unit myunit.test;
interface
var
a: longint;
implementation
initialization
a:=1;
end.
The following program will resolve myunit.test.a to the variable a in unit myunit.test:
227
CHAPTER 16. PROGRAMS, UNITS, BLOCKS
uses
myunit, myunit.test;
begin
Writeln(’myunit.test.a : ’,myunit.test.a);
end.
So it will print:
myunit.test.a : 1
uses
myunit.test, myunit;
begin
Writeln(’myunit.test.a : ’,myunit.test.a);
end.
myunit.test.a : 1
Similarly, the following program will resolve myunit.test.a to the variable a in unit myunit.test:
uses
myunit.test, myunit;
begin
Writeln(’a : ’,a);
end.
it will print:
a : 1
Similarly, the following program will resolve test.a to the variable test.a in unit myunit:
uses
myunit.test, myunit;
begin
Writeln(’test.a : ’,test.a);
end.
will print
test.a : 2
228
CHAPTER 16. PROGRAMS, UNITS, BLOCKS
Note that the identifiers from a unit on which a program depends indirectly, are not accessible to the
program. To have access to the identifiers of a unit, the unit must be in the uses clause of the program
or unit where the identifiers are needed.
Units can be mutually dependent, that is, they can reference each other in their uses clauses. This is
allowed, on the condition that at least one of the references is in the implementation section of the
unit. This also holds for indirect mutually dependent units.
If it is possible to start from one interface uses clause of a unit, and to return there via uses clauses
of interfaces only, then there is circular unit dependence, and the compiler will generate an error. For
example, the following is not allowed:
Unit UnitA;
interface
Uses UnitB;
implementation
end.
Unit UnitB
interface
Uses UnitA;
implementation
end.
Unit UnitA;
interface
Uses UnitB;
implementation
end.
Unit UnitB
implementation
Uses UnitA;
end.
16.5 Blocks
Units and programs are made of blocks. A block is made of declarations of labels, constants, types,
variables and functions or procedures. Blocks can be nested in certain ways, i.e., a procedure or
function declaration can have blocks in themselves. A block looks like the following:
Blocks
-
- block declaration part statement part -
229
CHAPTER 16. PROGRAMS, UNITS, BLOCKS
-
- declaration part -
6 label declaration part
constant declaration part
resourcestring declaration part
type declaration part
variable declaration part
threadvariable declaration part
procedure/function declaration part
-
- label declaration part label label ; -
6,
-
- constant declaration part const constant declaration -
6 typed constant declaration
-
- resourcestring declaration part resourcestring string constant declaration -
6
- -
-
- type declaration part type type declaration -
6
-
- variable declaration part var variable declaration -
6
-
- threadvariable declaration part threadvar variable declaration -
6
-
- procedure/function declaration part procedure declaration -
6 function declaration
constructor declaration
destructor declaration
-
- statement part compound statement -
Labels that can be used to identify statements in a block are declared in the label declaration part of
that block. Each label can only identify one statement.
Constants that are to be used only in one block should be declared in that block’s constant declaration
part.
Variables that are to be used only in one block should be declared in that block’s variable declaration
part.
Types that are to be used only in one block should be declared in that block’s type declaration part.
Lastly, functions and procedures that will be used in that block can be declared in the procedure/-
function declaration part.
These 4 declaration parts can be intermixed, there is no required order other than that you cannot use
(or refer to) identifiers that have not yet been declared.
After the different declaration parts comes the statement part. This contains any actions that the block
should execute. All identifiers declared before the statement part can be used in that statement part.
230
CHAPTER 16. PROGRAMS, UNITS, BLOCKS
16.6 Scope
Identifiers are valid from the point of their declaration until the end of the block in which the dec-
laration occurred. The range where the identifier is known is the scope of the identifier. The exact
scope of an identifier depends on the way it was defined.
Program Demo;
Var X : Real;
{ X is real variable }
Procedure NewDeclaration
Var X : Integer; { Redeclare X as integer}
begin
// X := 1.234; {would give an error when trying to compile}
X := 10; { Correct assignment}
end;
{ From here on, X is Real again}
begin
X := 2.468;
end.
In this example, inside the procedure, X denotes an integer variable. It has its own storage space,
independent of the variable X outside the procedure.
231
CHAPTER 16. PROGRAMS, UNITS, BLOCKS
unit unitA;
interface
Type
MyType = Real;
implementation
end.
Program prog;
Uses UnitA;
{ Redeclaration of MyType}
Type MyType = Integer;
Var A : Mytype; { Will be Integer }
B : UnitA.MyType { Will be real }
begin
end.
16.7 Libraries
Free Pascal supports making of dynamic libraries (DLLs under Win32 and OS /2) trough the use of
the Library keyword.
A Library is just like a unit or a program:
Libraries
-
- library library header ; block . -
uses clause
-
- library header library identifier -
By default, functions and procedures that are declared and implemented in library are not available
to a programmer that wishes to use this library.
In order to make functions or procedures available from the library, they must be exported in an
exports clause:
232
CHAPTER 16. PROGRAMS, UNITS, BLOCKS
Exports clause
-
- exports clause exports exports list ; -
-
- exports list exports entry -
6 ,
Under Win32, an index clause can be added to an exports entry. An index entry must be a positive
number larger or equal than 1, and less than MaxInt.
Optionally, an exports entry can have a name specifier. If present, the name specifier gives the exact
name (case sensitive) by which the function will be exported from the library.
If neither of these constructs is present, the functions or procedures are exported with the exact names
as specified in the exports clause.
233
Chapter 17
Exceptions
Exceptions provide a convenient way to program error and error-recovery mechanisms, and are
closely related to classes. Exception support is based on 3 constructs:
Raise statements. To raise an exception. This is usually done to signal an error condition. It is
however also usable to abort execution and immediately return to a well-known point in the
executable.
Try ... Except blocks. These block serve to catch exceptions raised within the scope of the block,
and to provide exception-recovery code.
Try ... Finally blocks. These block serve to force code to be executed irrespective of an exception
occurrence or not. They generally serve to clean up memory or close files in case an exception
occurs. The compiler generates many implicit Try ... Finally blocks around proce-
dure, to force memory consistency.
Raise statement
-
- raise statement raise -
exception instance
exception address
-
- exception address at exception address -
, address expression
This statement will raise an exception. If it is specified, the exception instance must be an initialized
instance of any class, which is the raise type. The exception address and frame are optional. If they
are not specified, the compiler will provide the address by itself. If the exception instance is omitted,
then the current exception is re-raised. This construct can only be used in an exception handling
block (see further).
Remark: Control never returns after an exception block. The control is transferred to the first try...finally
or try...except statement that is encountered when unwinding the stack. If no such statement
234
CHAPTER 17. EXCEPTIONS
is found, the Free Pascal Run-Time Library will generate a run-time error 217 (see also section 17.5,
page 238). The exception address will be printed by the default exception handling routines.
As an example: The following division checks whether the denominator is zero, and if so, raises an
exception of type EDivException
The class Exception is defined in the Sysutils unit of the rtl. (section 17.5, page 238)
Remark: Although the Exception class is used as the base class for exceptions throughout the code, this
is just an unwritten agreement: the class can be of any type, and need not be a descendent of the
Exception class.
Of course, most code depends on the unwritten agreement that an exception class descends from
Exception.
The following code shows how to omit an error reporting routine from the stack shown in the excep-
tion handler:
{$mode objfpc}
uses sysutils;
begin
raise exception.create(Msg) at
get_caller_addr(get_frame),
get_caller_frame(get_frame);
end;
procedure test2;
begin
error(’Error’);
end;
begin
test2;
end.
Line 15 is in procedure Test2, not in Error, which actually raised the exception.
235
CHAPTER 17. EXCEPTIONS
Try..except statement
-
- try statement try statement list except exceptionhandlers end -
-
- statement list statement -
6 ;
-
- exceptionhandlers -
exception handler
6 ; else statement list
statement list
- exception handler on
- class type identifier do statement -
identifier :
If no exception is raised during the execution of the statement list, then all statements in the
list will be executed sequentially, and the except block will be skipped, transferring program flow to
the statement after the final end.
If an exception occurs during the execution of the statement list, the program flow will be
transferred to the except block. Statements in the statement list between the place where the exception
was raised and the exception block are ignored.
In the exception handling block, the type of the exception is checked, and if there is an exception
handler where the class type matches the exception object type, or is a parent type of the exception
object type, then the statement following the corresponding Do will be executed. The first matching
type is used. After the Do block was executed, the program continues after the End statement.
The identifier in an exception handling statement is optional, and declares an exception object. It
can be used to manipulate the exception object in the exception handling code. The scope of this
declaration is the statement block following the Do keyword.
If none of the On handlers matches the exception object type, then the statement list after else is
executed. If no such list is found, then the exception is automatically re-raised. This process allows
to nest try...except blocks.
If, on the other hand, the exception was caught, then the exception object is destroyed at the end of
the exception handling block, before program flow continues. The exception is destroyed through a
call to the object’s Destroy destructor.
As an example, given the previous declaration of the DoDiv function, consider the following
Try
Z := DoDiv (X,Y);
Except
On EDivException do Z := 0;
end;
If Y happens to be zero, then the DoDiv function code will raise an exception. When this happens,
program flow is transferred to the except statement, where the Exception handler will set the value
of Z to zero. If no exception is raised, then program flow continues past the last end statement. To
allow error recovery, the Try ... Finally block is supported. A Try...Finally block
ensures that the statements following the Finally keyword are guaranteed to be executed, even if
an exception occurs.
236
CHAPTER 17. EXCEPTIONS
Try...finally statement
-
- trystatement try statement list finally finally statements end -
-
- finally statements statementlist -
If no exception occurs inside the statement List, then the program runs as if the Try, Finally
and End keywords were not present, unless an exit command is given: an exit command first exe-
cutes all statements in the finally blocks before actually exiting.
If, however, an exception occurs, the program flow is immediately transferred from the point where
the exception was raised to the first statement of the Finally statements.
All statements after the finally keyword will be executed, and then the exception will be automatically
re-raised. Any statements between the place where the exception was raised and the first statement
of the Finally Statements are skipped.
As an example consider the following routine:
If during the execution of the file handling an exception occurs, then program flow will continue at
the close(F) statement, skipping any file operations that might follow between the place where
the exception was raised, and the Close statement. If no exception occurred, all file operations will
be executed, and the file will be closed at the end.
Note that an Exit statement enclosed by a try .. finally block, will still execute the finally
block. Reusing the previous example:
237
CHAPTER 17. EXCEPTIONS
if B then
exit; // Stop processing prematurely
// More file handling
Finally
Close(F);
end;
end;
The file will still be closed, even if the processing ends prematurely using the Exit statement.
Exception = class(TObject)
private
fmessage : string;
fhelpcontext : longint;
public
constructor create(const msg : string);
constructor createres(indent : longint);
property helpcontext : longint read fhelpcontext write fhelpcontext;
property message : string read fmessage write fmessage;
end;
ExceptClass = Class of Exception;
And uses this declaration to define quite a number of exceptions, for instance:
{ mathematical exceptions }
EIntError = class(Exception);
EDivByZero = class(EIntError);
ERangeError = class(EIntError);
EIntOverflow = class(EIntError);
EMathError = class(Exception);
The SysUtils unit also installs an exception handler. If an exception is unhandled by any exception
handling block, this handler is called by the Run-Time library. Basically, it prints the exception
address, and it prints the message of the Exception object, and exits with an exit code of 217. If the
238
CHAPTER 17. EXCEPTIONS
exception object is not a descendent object of the Exception object, then the class name is printed
instead of the exception message.
It is recommended to use the Exception object or a descendant class for all raise statements,
since then the message field of the exception object can be used.
239
Chapter 18
Using assembler
Free Pascal supports the use of assembler in code, but not inline assembler macros. To have more
information on the processor specific assembler syntax and its limitations, see the Programmer’s
Guide.
...
Statements;
...
Asm
the asm code here
...
end;
...
Statements;
The assembler instructions between the Asm and end keywords will be inserted in the assembler
generated by the compiler. Conditionals can be used in assembler code, the compiler will recognise
them, and treat them as any other conditionals.
240
Index
Abstract, 78 Dispatch, 95
Address, 162 DispatchStr, 95
Alias, 206 Double, 30
Ansistring, 32, 37
Array, 41, 195, 196 else, 174, 175
Constructor, 45 except, 236, 238
Dynamic, 42 Exception, 234
Of const, 196 Exceptions, 234
Static, 41 Catching, 234, 236
array, 58 Classes, 238
Array constructor, 45 Handling, 237, 238
Asm, 188 Raising, 234
Assembler, 188, 205, 240 export, 207
Expression, 185, 186
block, 229 Expressions, 155
Boolean, 27 Extended, 30
Extended records, 130
Case, 174 External, 204
cdecl, 206 external, 64, 204
Char, 30
Class, 82, 91 Fields, 47, 72
Class helpers, 135 File, 51
Classes, 82 finally, 237, 238
CodePage, 32, 34 For, 177, 178
Conversion, 34 downto, 177
COM, 58, 112 in, 178
Comments, 12 to, 177
Comp, 30 Forward, 53, 203
Const, 22 Function, 190
String, 22 Functions, 189
Constants, 20 Assembler, 205, 240
Ordinary, 20 External, 204
String, 18, 21, 37 Forward, 203
Typed, 21 Modifiers, 205
Constructor, 74, 87, 159 Overloaded, 202
CORBA, 58, 112
Currency, 30 Generics, 114
Overloads, 121
Delphi Type Restrictions, 119
Compatibility, 120
Syntax, 120 Hint directives, 15
Type overloads, 121
Identifiers, 15
Destructor, 74, 88
If, 175
Directives
index, 99, 204
Hint, 15
Inherited, 90
241
INDEX
242
INDEX
Record, 47 Symbols, 11
Constant, 66 Syntax diagrams, 9
Record helpers, 135
register, 211 Text, 51
reintroduce, 90 then, 175
Repeat, 185 Thread Variables, 67
Reserved words, 13 Threadvar, 67
Delphi, 14 Tokens, 11
Modifiers, 14 Comments, 12
Turbo Pascal, 13 Identifiers, 15
Resourcestring, 22 Numbers, 16
Reserved words, 13
safecall, 211 Strings, 18
saveregisters, 211 Symbols, 11
Scope, 33, 44, 65, 71, 80, 83, 231 try, 237, 238
block, 231 Type, 24
Class, 231 Compatibility, 27, 45, 61, 122, 160, 162,
record, 231 192
unit, 232 Generics, 114
Self, 75, 91, 96 Helpers, 135
Set, 50 Restrictions, 119
Shortstring, 32 Type overloads, 121
Single, 30 Typecast, 33, 34, 37, 160, 161
softfloat, 211 Unaligned, 161
Statements, 170 Value, 160
Assembler, 188, 240 Variable, 160
Assignment, 170 Types, 24
Case, 174 Ansistring, 32
Compound, 173 Array, 41, 42
Exception, 188 Base, 24
For, 177, 178 Boolean, 27
Goto, 172 Char, 30
if, 175 Class, 82
Loop, 177, 178, 185 Class helpers, 135
Procedure, 171 Constructor, 45
Repeat, 185 Enumeration, 28
Simple, 170 Extended record, 130
Structured, 173 File, 51
While, 185 Forward declaration, 53
With, 186 Integer, 25
Static class methods, 93 Object, 71
stdcall, 211 Ordinal, 25
String, 18 PChar, 34, 38
Ansistring, 32 Pointer, 38, 51
CodePage, 32 Procedural, 54
Codepage, 34 Rawbytestring, 36
Constant, 37 Real, 29
Multi-byte, 37 Record, 47
RawByteString, 36 Record helpers, 135
ShortString, 32 Reference counted, 32, 34, 36, 37, 42, 44,
Single-byte string, 31 112, 198
UnicodeString, 37 Set, 50
UTF8String, 36 ShortString, 32
WideString, 37 String, 31
243
INDEX
Structured, 39
Subrange, 29
Type helpers, 135
UnicodeString, 36, 37
UTF8String, 36
Variant, 57
Widestring, 37
Unicodestring, 37
unit, 224, 232
uses, 223
UTF8String, 36
Var, 63
varargs, 211
Variable, 63
Variables, 63
Initialized, 21, 65, 66
Variant, 57
Virtual, 74, 75, 77, 90, 95
Visibility, 71, 80, 106
Private, 71, 84
Protected, 84
Public, 71, 84
Published, 84
Strict Private, 84
Strict Protected, 84
While, 185
WideChar, 30
Widestring, 37
With, 186
Write, 98
244