Delphi Language Guide 10.3
Delphi Language Guide 10.3
Embarcadero tools are built for elite developers who build and maintain the
world’s most critical applications. Our customers choose Embarcadero
because we are the champion of developers, and we help them build more
secure and scalable enterprise applications faster than any other tools on the
market. In fact, ninety of the Fortune 100 and an active community of more
than three million users worldwide have relied on Embarcadero's award-winning
products for over 30 years.
We invite you to try our products for free and see for yourself.
www.embarcadero.com/products/rad-studio/start-for-free
November, 2019
Embarcadero Technologies 2
CONTENTS
Language Overview....................................................................................................... 15
Program Organization ................................................................................................ 15
Delphi Source Files ................................................................................................... 16
Other Files Used to Build Applications .................................................................. 16
Compiler-Generated Files ...................................................................................... 17
Example Programs ...................................................................................................... 17
A Simple Console Application ............................................................................... 18
A More Complicated Example ............................................................................. 19
A VCL Application ................................................................................................... 20
Programs and Units Index .............................................................................................. 23
Topics ............................................................................................................................ 23
Programs and Units (Delphi) .......................................................................................... 24
Program Structure and Syntax .................................................................................. 24
The Program Heading ............................................................................................. 24
The Program Uses Clause ....................................................................................... 25
The Block ................................................................................................................... 25
Unit Structure and Syntax ........................................................................................... 26
The Unit Heading ..................................................................................................... 27
The Interface Section .............................................................................................. 27
The Implementation Section .................................................................................. 27
The Initialization Section .......................................................................................... 28
The Finalization Section ........................................................................................... 28
Unit References and the Uses Clause ...................................................................... 29
The Syntax of a Uses Clause ................................................................................... 29
Multiple and Indirect Unit References .................................................................. 30
Circular Unit References ......................................................................................... 31
Using Namespaces with Delphi .................................................................................... 32
Declaring Namespaces ............................................................................................. 33
Searching Namespaces ............................................................................................. 34
Namespace search order ...................................................................................... 34
A namespace search example ............................................................................ 34
Using Namespaces ..................................................................................................... 35
Fully qualified unit names ....................................................................................... 35
Multi-unit Namespaces ........................................................................................... 36
Fundamental Syntactic Elements Index ...................................................................... 37
Topics ............................................................................................................................ 37
Fundamental Syntactic Elements (Delphi) ................................................................. 38
The Delphi Character Set ........................................................................................... 38
Tokens ............................................................................................................................ 39
Special Symbols ....................................................................................................... 39
Identifiers ................................................................................................................... 40
Embarcadero Technologies 3
Reserved Words ....................................................................................................... 41
Directives................................................................................................................... 42
Numerals ................................................................................................................... 44
Labels......................................................................................................................... 45
Character Strings ..................................................................................................... 45
Comments and Compiler Directives ........................................................................ 46
in ........................................................................................................................................ 47
Expressions (Delphi)......................................................................................................... 48
Expressions .................................................................................................................... 48
Operators...................................................................................................................... 49
Arithmetic Operators .............................................................................................. 49
Boolean Operators .................................................................................................. 50
Complete Versus Short-Circuit Boolean Evaluation ........................................... 51
Logical (Bitwise) Operators .................................................................................... 52
String Operators ....................................................................................................... 54
Pointer Operators .................................................................................................... 54
Set Operators ........................................................................................................... 55
Relational Operators ............................................................................................... 56
Class and Interface Operators .............................................................................. 58
The @ Operator ........................................................................................................ 58
Operator Precedence ............................................................................................ 58
Function Calls ............................................................................................................... 60
Set Constructors ........................................................................................................... 61
Indexes .......................................................................................................................... 61
Typecasts ...................................................................................................................... 62
Value Typecasts ....................................................................................................... 62
Variable Typecasts .................................................................................................. 62
Declarations and Statements (Delphi) ........................................................................ 64
Declarations ................................................................................................................. 64
Hinting Directives ..................................................................................................... 65
Statements ................................................................................................................... 66
Simple Statements ....................................................................................................... 66
Assignment Statements .......................................................................................... 66
Procedure and Function Calls ............................................................................... 67
Goto Statements ..................................................................................................... 67
Structured Statements ................................................................................................ 69
Compound Statements .......................................................................................... 70
With Statements ....................................................................................................... 70
If Statements ............................................................................................................. 74
Case Statements ..................................................................................................... 76
Control Loops ........................................................................................................... 77
Blocks and Scope........................................................................................................ 86
Blocks ......................................................................................................................... 86
Scope ........................................................................................................................ 87
Embarcadero Technologies 4
Naming Conflicts ..................................................................................................... 87
Data Types, Variables, and Constants Index ............................................................. 88
Topics ............................................................................................................................ 88
About Data Types (Delphi) ............................................................................................ 89
Simple Types (Delphi) ..................................................................................................... 91
Ordinal Types ............................................................................................................... 91
Integer Types ............................................................................................................ 92
Character Types ...................................................................................................... 95
Boolean Types .......................................................................................................... 96
Enumerated Types ................................................................................................... 97
Subrange Types...................................................................................................... 102
Real Types ................................................................................................................... 104
String Types (Delphi) ..................................................................................................... 105
About String Types ..................................................................................................... 106
Short Strings................................................................................................................. 108
AnsiString ..................................................................................................................... 109
UnicodeString (the Default String Type) ................................................................. 110
WideString ................................................................................................................... 111
Working with null-Terminated Strings ...................................................................... 111
Using Pointers, Arrays, and String Constants ...................................................... 112
Mixing Delphi Strings and Null-Terminated Strings ............................................ 113
Structured Types (Delphi) ............................................................................................. 115
Alignment of Structured Types ................................................................................ 115
Sets ............................................................................................................................... 115
Arrays ........................................................................................................................... 117
Static Arrays ............................................................................................................ 117
Dynamic Arrays ...................................................................................................... 118
Multidimensional Dynamic Arrays ....................................................................... 121
Array Types and Assignments .............................................................................. 122
String-Like Operations Supported on Dynamic Arrays..................................... 122
Records (traditional) ................................................................................................. 123
Variant Parts in Records ........................................................................................ 125
Records (advanced) ................................................................................................ 127
File Types (Win32)....................................................................................................... 128
Code Samples ........................................................................................................... 129
Pointers and Pointer Types (Delphi)............................................................................ 130
Overview of pointers ................................................................................................. 130
Using Extended Syntax with Pointers .................................................................. 132
Pointer Types .............................................................................................................. 132
Character Pointers ................................................................................................ 133
Byte Pointer ............................................................................................................. 133
Type-checked Pointers ......................................................................................... 133
Other Standard Pointer Types .............................................................................. 133
Procedural Types (Delphi) ........................................................................................... 134
Embarcadero Technologies 5
About Procedural Types ........................................................................................... 135
Method Pointers ..................................................................................................... 135
Procedural Types in Statements and Expressions ................................................. 137
Variant Types (Delphi) .................................................................................................. 138
Variants Overview ..................................................................................................... 138
Variant Type Conversions ........................................................................................ 140
Variants in Expressions............................................................................................... 142
Variant Arrays ............................................................................................................. 142
OleVariant .................................................................................................................. 143
Type Compatibility and Identity (Delphi) .................................................................. 143
Type Identity ............................................................................................................... 144
Type Compatibility .................................................................................................... 144
Assignment Compatibility ........................................................................................ 145
Data Types, Variables, and Constants Index (Delphi) ............................................ 146
Type Declaration Syntax .......................................................................................... 146
Variables (Delphi) ......................................................................................................... 148
Declaring Variables .................................................................................................. 148
Absolute Addresses ............................................................................................... 149
Dynamic Variables ................................................................................................ 150
Thread-local Variables .......................................................................................... 150
Declared Constants...................................................................................................... 151
True Constants ........................................................................................................... 151
Constant Expressions ............................................................................................. 154
Resource Strings ..................................................................................................... 155
Typed Constants ........................................................................................................ 155
Array Constants...................................................................................................... 155
Record Constants .................................................................................................. 156
Procedural Constants ........................................................................................... 157
Pointer Constants ................................................................................................... 157
Writeable Typed Constants .................................................................................. 158
Procedures and Functions Index ................................................................................ 159
Topics .......................................................................................................................... 159
Procedures and Functions (Delphi)............................................................................ 160
About Procedures and Functions ........................................................................... 160
Declaring Procedures and Functions ..................................................................... 160
Procedure Declarations ....................................................................................... 161
Function Declarations ........................................................................................... 161
Calling Conventions.................................................................................................. 163
Forward and Interface Declarations ...................................................................... 165
External Declarations ................................................................................................ 165
Linking to Object Files ........................................................................................... 166
Importing Functions from Libraries ...................................................................... 166
Overloading Procedures and Functions ................................................................ 168
Local Declarations .................................................................................................... 171
Embarcadero Technologies 6
Nested Routines ..................................................................................................... 171
Parameters (Delphi)...................................................................................................... 172
About Parameters ..................................................................................................... 172
Parameter Semantics ............................................................................................... 173
Value and Variable Parameters ......................................................................... 173
Constant Parameters ............................................................................................ 174
Out Parameters ...................................................................................................... 175
Untyped Parameters ............................................................................................. 176
String Parameters ...................................................................................................... 177
Array Parameters ....................................................................................................... 177
Open Array Parameters ....................................................................................... 178
Variant Open Array Parameters ......................................................................... 180
Default Parameters ................................................................................................... 181
Default Parameters and Overloaded Functions .............................................. 182
Default Parameters in Forward and Interface Declarations .......................... 183
Calling Procedures and Functions (Delphi) .............................................................. 183
Program Control and Parameters .......................................................................... 183
Open Array Constructors ......................................................................................... 184
Using the inline Directive .......................................................................................... 184
Anonymous Methods in Delphi ................................................................................... 186
Syntax .......................................................................................................................... 186
Using Anonymous Methods ..................................................................................... 188
Anonymous Methods Variable Binding ................................................................. 189
Variable Binding Illustration .................................................................................. 189
Anonymous Methods as Events .......................................................................... 190
Variable Binding Mechanism............................................................................... 191
Utility of Anonymous Methods ................................................................................. 193
Variable Binding..................................................................................................... 193
Ease of Use .............................................................................................................. 194
Using Code for a Parameter ................................................................................ 195
Classes and Objects Index .......................................................................................... 197
Topics .......................................................................................................................... 197
Classes and Objects (Delphi) ...................................................................................... 198
Class Types ................................................................................................................. 198
Inheritance and Scope ............................................................................................ 200
TObject and TClass ................................................................................................ 201
Compatibility of Class Types ................................................................................ 201
Object Types .......................................................................................................... 201
Visibility of Class Members ....................................................................................... 202
Private, Protected, and Public Members .......................................................... 203
Strict Visibility Specifiers ......................................................................................... 203
Published Members ............................................................................................... 204
Automated Members (Win32 Only).................................................................... 205
Forward Declarations and Mutually Dependent Classes ................................... 205
Embarcadero Technologies 7
Fields (Delphi) ................................................................................................................ 206
About Fields ................................................................................................................ 206
Class Fields .................................................................................................................. 207
Methods (Delphi) .......................................................................................................... 208
About Methods .......................................................................................................... 209
Inherited .................................................................................................................. 210
Self ............................................................................................................................ 210
Method Binding ......................................................................................................... 211
Static Methods ....................................................................................................... 211
Virtual and Dynamic Methods ............................................................................ 212
Class Methods ............................................................................................................ 215
Ordinary Class Methods ....................................................................................... 215
Class Static Methods ............................................................................................. 216
Overloading Methods .............................................................................................. 216
Constructors ............................................................................................................... 217
Destructors .................................................................................................................. 219
Class Constructors ..................................................................................................... 220
Class Destructors........................................................................................................ 221
Message Methods ..................................................................................................... 222
Implementing Message Methods ....................................................................... 223
Message Dispatching ........................................................................................... 223
Properties (Delphi) ........................................................................................................ 224
About Properties ........................................................................................................ 224
Property Access ......................................................................................................... 225
Array Properties ......................................................................................................... 227
Index Specifiers .......................................................................................................... 229
Storage Specifiers ...................................................................................................... 229
Property Overrides and Redeclarations ................................................................ 230
Class Properties .......................................................................................................... 232
Events (Delphi) ............................................................................................................... 233
About Events .............................................................................................................. 233
Event Properties and Event Handlers ..................................................................... 233
Triggering Multiple Event Handlers ......................................................................... 235
Class References ........................................................................................................... 236
Class-Reference Types ............................................................................................. 236
Constructors and Class References .................................................................... 237
Class Operators ......................................................................................................... 238
The is Operator ....................................................................................................... 238
The as Operator ..................................................................................................... 238
Code Examples ......................................................................................................... 239
Exceptions (Delphi) ....................................................................................................... 240
About Exceptions ...................................................................................................... 240
When To Use Exceptions........................................................................................... 240
Declaring Exception Types ...................................................................................... 241
Embarcadero Technologies 8
Raising and Handling Exceptions ........................................................................... 242
Try...except Statements ........................................................................................ 243
Re-raising Exceptions ............................................................................................ 245
Nested Exceptions ................................................................................................. 246
Try...finally Statements ........................................................................................... 247
Standard Exception Classes and Routines ............................................................ 247
Class and Record Helpers (Delphi) ............................................................................ 248
About Class and Record Helpers............................................................................ 248
Helper Syntax ............................................................................................................. 248
Using Helpers .............................................................................................................. 249
Nested Type Declarations ........................................................................................... 250
Declaring Nested Types ........................................................................................... 250
Declaring and Accessing Nested Classes ............................................................. 251
Nested Constants ...................................................................................................... 251
Operator Overloading (Delphi) .................................................................................. 252
About Operator Overloading ................................................................................. 252
Declaring Operator Overloads ............................................................................... 255
Code Samples ........................................................................................................... 256
Standard Routines and Input-Output ........................................................................ 257
File Input and Output................................................................................................ 257
Text Files ................................................................................................................... 260
Untyped Files .......................................................................................................... 261
Text File Device Drivers ............................................................................................. 261
The Open function ................................................................................................ 262
The InOut function ................................................................................................. 262
The Flush function .................................................................................................. 263
The Close function ................................................................................................. 263
Handling null-Terminated Strings ............................................................................. 263
Null-Terminated String Functions ......................................................................... 263
Wide-Character Strings ......................................................................................... 265
Other Standard Routines .......................................................................................... 265
Libraries and Packages Index ..................................................................................... 270
Topics .......................................................................................................................... 270
Libraries and Packages (Delphi)................................................................................. 271
Calling Dynamically Loadable Libraries ................................................................ 271
Static Loading ............................................................................................................ 271
Delayed Loading (Windows-only) .......................................................................... 272
Dynamic Loading ...................................................................................................... 272
Writing Dynamically Loaded Libraries ....................................................................... 274
Using Export Clause in Libraries ............................................................................... 274
Library Initialization Code ......................................................................................... 276
Global Variables in a Library ................................................................................... 277
Libraries and System Variables ................................................................................ 277
Exceptions and Runtime Errors in Libraries ............................................................. 278
Embarcadero Technologies 9
Shared-Memory Manager ....................................................................................... 278
Packages (Delphi) ........................................................................................................ 279
Understanding Packages ........................................................................................ 279
Package Declarations and Source Files................................................................ 280
Naming packages ................................................................................................ 281
The requires clause ................................................................................................ 281
Avoiding circular package references .............................................................. 281
Duplicate package references .......................................................................... 282
The contains clause............................................................................................... 282
Avoiding redundant source code uses ............................................................. 282
Compiling Packages ................................................................................................ 282
Generated Files...................................................................................................... 282
Package-Specific Compiler Directives .............................................................. 283
Package-Specific Command-Line Compiler Switches ................................... 284
Object Interfaces Index ............................................................................................... 284
Topics .......................................................................................................................... 284
Object Interfaces (Delphi) ........................................................................................... 285
Interface Types .......................................................................................................... 285
IInterface and Inheritance....................................................................................... 286
Interface Identification and GUIDs......................................................................... 287
Calling Conventions for Interfaces ......................................................................... 288
Interface Properties................................................................................................... 288
Forward Declarations ............................................................................................... 288
Implementing Interfaces.............................................................................................. 288
Class Declarations ..................................................................................................... 289
Method Resolution Clause ....................................................................................... 290
Changing Inherited Implementations .................................................................... 290
Implementing Interfaces by Delegation ............................................................... 291
Delegating to an Interface-Type Property ........................................................ 291
Delegating to a Class-Type Property .................................................................. 293
Interface References (Delphi) .................................................................................... 293
Implementing Interface References ...................................................................... 293
Interface Assignment Compatibility ....................................................................... 295
Interface Typecasts ................................................................................................... 295
Interface Querying .................................................................................................... 296
Casting Interface References to Objects ............................................................. 296
Automation Objects (Win32 Only) ............................................................................. 298
Dispatch Interface Types ......................................................................................... 298
Dispatch interface methods .................................................................................... 298
Dispatch interface properties ................................................................................. 299
Accessing Automation Objects .............................................................................. 299
Automation Object Method-Call Syntax .............................................................. 299
Dual Interfaces .......................................................................................................... 300
Memory Management Index...................................................................................... 301
Embarcadero Technologies 10
Topics .......................................................................................................................... 301
Memory Management ................................................................................................ 301
Default memory manager ....................................................................................... 301
The FastMM Memory Manager (Win32 and Win64) ............................................ 301
The Posix Memory Manager (Posix platforms) ...................................................... 303
Variables ..................................................................................................................... 303
Internal Data Formats (Delphi).................................................................................... 304
Integer Types .............................................................................................................. 304
Platform-Independent Unsigned Integer Types ................................................ 304
Platform-Independent Signed Integer Types .................................................... 305
Platform-Dependent Integer Types .................................................................... 307
Integer Subrange Types ........................................................................................... 308
Character Types ........................................................................................................ 308
Boolean Types ............................................................................................................ 309
Enumerated Types .................................................................................................... 309
Real Types ................................................................................................................... 309
The Real48 type ..................................................................................................... 309
The Single type ....................................................................................................... 310
The Double type .................................................................................................... 310
The Extended type ................................................................................................ 311
The Comp type ...................................................................................................... 311
The Currency type ................................................................................................. 311
Pointer Types .............................................................................................................. 311
Short String Types ....................................................................................................... 312
Long String Types ....................................................................................................... 312
Wide String Types ....................................................................................................... 313
Set Types ..................................................................................................................... 314
Static Array Types ...................................................................................................... 314
Dynamic Array Types ................................................................................................ 315
Record Types.............................................................................................................. 315
File Types ..................................................................................................................... 317
Procedural Types ....................................................................................................... 319
Class Types ................................................................................................................. 319
Class Reference Types .............................................................................................. 323
Variant Types .............................................................................................................. 323
Program Control (Delphi)............................................................................................. 324
Passing Parameters ................................................................................................... 324
By Value vs. By Reference .................................................................................... 324
Pascal, cdecl, stdcall, and safecall Conventions ............................................ 325
Register Convention .............................................................................................. 326
Register saving conventions ................................................................................ 326
Handling Function Results ........................................................................................ 326
Handling Method Calls ............................................................................................. 327
Understanding Exit Procedures ............................................................................... 328
Embarcadero Technologies 11
Inline Assembly Code Index ........................................................................................ 330
Topics .......................................................................................................................... 330
Using Inline Assembly Code ........................................................................................ 331
Using the asm Statement ......................................................................................... 331
Using Registers ............................................................................................................ 332
32-bit ........................................................................................................................ 332
64-bit ........................................................................................................................ 332
Using Conditional Defines for Cross-Platform Code ............................................ 332
Assembler Syntax .......................................................................................................... 333
Statements ................................................................................................................. 333
Labels .......................................................................................................................... 334
Instruction Opcodes ................................................................................................. 334
Automatic jump sizing........................................................................................... 335
Directives .................................................................................................................... 335
Operands.................................................................................................................... 339
Assembly Expressions .................................................................................................... 340
Differences between Delphi and Assembler Expressions ................................... 340
Expression Elements .................................................................................................. 341
Numeric Constants ................................................................................................ 341
String Constants ..................................................................................................... 342
Registers .................................................................................................................. 343
Symbols ................................................................................................................... 345
Expression Classes ..................................................................................................... 347
Expression Types......................................................................................................... 349
Expression Operators ................................................................................................ 350
Assembly Procedures and Functions ......................................................................... 353
Compiler Optimizations ............................................................................................ 353
Function Results ......................................................................................................... 354
32-bit ........................................................................................................................ 354
64-bit ........................................................................................................................ 354
Intel 64 Specifics (Pseudo-Ops) ............................................................................... 354
Stack Unwinding for PC-mapped Exceptions ...................................................... 355
Generics Index .............................................................................................................. 355
Topics .......................................................................................................................... 355
Overview of Generics................................................................................................... 356
How Generics Work................................................................................................... 356
Code Examples ......................................................................................................... 356
Platform Requirements and Differences................................................................ 358
Run-time type identification ................................................................................ 358
Interface GUID ....................................................................................................... 358
Parameterized method in interface ................................................................... 358
Instantiation timing ................................................................................................ 358
Dynamic instantiation ........................................................................................... 358
Interface constraints ............................................................................................. 358
Embarcadero Technologies 12
Terminology for Generics ............................................................................................. 359
Declaring Generics ....................................................................................................... 360
Type Argument .......................................................................................................... 360
Nested Types .............................................................................................................. 361
Base Types .................................................................................................................. 362
Class, Interface, and Record Types........................................................................ 362
Procedural Types ....................................................................................................... 362
Parameterized Methods........................................................................................... 363
Scope of Type Parameters ...................................................................................... 364
Overloads and Type Compatibility in Generics ....................................................... 365
Overloads ................................................................................................................... 365
Type Compatibility .................................................................................................... 365
Constraints in Generics................................................................................................. 366
Specifying Generics with Constraints ..................................................................... 366
Declaring Constraints ............................................................................................ 366
Multiple Type Parameters ..................................................................................... 366
Multiple Constraints ............................................................................................... 367
Types of Constraints .................................................................................................. 367
Interface Type Constraints ................................................................................... 367
Class Type Constraints .......................................................................................... 368
Constructor Constraints ........................................................................................ 368
Class Constraint ..................................................................................................... 368
Record Constraint ................................................................................................. 368
Type Inferencing ........................................................................................................ 369
Class Variable in Generics ........................................................................................... 369
Attributes and RTTI ......................................................................................................... 371
Introduction ................................................................................................................ 371
Attributes and RTTI ..................................................................................................... 371
Topics .......................................................................................................................... 371
Declaring Custom Attributes (RTTI) ............................................................................. 372
Declaring an Attribute .............................................................................................. 372
Attribute Names that End with 'Attribute' are Implicitly Shortened ............... 372
Constructors in Attributes ......................................................................................... 373
Annotating Types and Type Members ...................................................................... 373
General Syntax .......................................................................................................... 373
You Can Only Use Constant Expressions as Attribute Parameters .................... 374
Extracting Attributes at Run Time ................................................................................ 375
Attribute Instantiation ............................................................................................... 376
Exceptions .................................................................................................................. 377
Using Virtual Method Interceptors .............................................................................. 378
Compiler Attributes ....................................................................................................... 378
Ref ................................................................................................................................ 378
Unsafe ......................................................................................................................... 379
Volatile ........................................................................................................................ 379
Embarcadero Technologies 13
Weak ........................................................................................................................... 379
Writing C++-friendly Delphi Code............................................................................... 379
DOs .............................................................................................................................. 380
Redeclaring All Inhereted Contructors .............................................................. 380
Ensuring Distinct Signature for Each Constructor in a Hierarchy .................... 380
DON'Ts ......................................................................................................................... 382
Overloading Index Properties .............................................................................. 382
Calling Virtual Mehtods from Constructors ........................................................ 382
Using Generics in Aliases ...................................................................................... 382
Using Generics in Closures .................................................................................... 382
Using Records with Constructors ......................................................................... 383
Using Non-Empty Default String Parameters ..................................................... 383
Embarcadero Technologies 14
Language Overview
Delphi is a high-level, compiled, strongly typed language that supports structured
and object-oriented design. Based on Delphi, its benefits include easy-to-read
code, quick compilation, and the use of multiple unit files for modular
programming. Delphi has special features that support the RAD Studio
component framework and environment. For the most part, descriptions and
examples in this language guide assume that you are using Embarcadero
development tools.
This language guide generally assumes that you are working in the IDE and that
you are building applications that use the Visual Component Library (VCL).
Occasionally, however, Delphi-specific rules are distinguished from rules that
apply to all Delphi programming.
o Program Organization. Covers the basic language features that allow you
to partition your application into units and namespaces.
Program Organization
Delphi programs are usually divided into source-code modules called units. Most
programs begin with a program heading, which specifies a name for the
program. The program heading is followed by an optional uses clause, then a
block of declarations and statements. The uses clause lists units that are linked
into the program; these units, which can be shared by different programs, often
have uses clauses of their own.
The uses clause provides the compiler with information about dependencies
among modules. Because this information is stored in the modules themselves,
most Delphi language programs do not require makefiles, header files, or
preprocessor "include" directives.
Embarcadero Technologies 15
Delphi Source Files
The compiler expects to find Delphi source code in files of three kinds:
Unit source files typically contain most of the code in an application. Each
application has a single project file and several unit files; the project file, which
corresponds to the program file in traditional Pascal, organizes the unit files into
an application. Embarcadero development tools automatically maintain a
project file for each application.
If you are compiling a program from the command line, you can put all your
source code into unit (.pas) files. If you use the IDE to build your application, it will
produce a project (.dpr) file.
Package source files are similar to project files, but they are used to construct
special dynamically linkable libraries called packages.
A VCL form file contains the description of the properties of the form and the
components it owns. Each form file represents a single form, which usually
corresponds to a window or dialog box in an application. The IDE allows you to
view and edit form files as text, and to save form files as either text (a format very
suitable for version control) or binary. Although the default behavior is to save
form files as text, they are usually not edited manually; it is more common to use
Embarcadero's visual design tools for this purpose. Each project has at least one
form, and each form has an associated unit (.pas) file that, by default, has the
same name as the form file.
In addition to VCL form files, each project uses a resource (.res) file to hold the
application's icon and other resources such as strings. By default, this file has the
same name as the project (.dpr) file.
A project options (.dof) file contains compiler and linker settings, search path
information, version information, and so forth. Each project has an associated
Embarcadero Technologies 16
project options file with the same name as the project (.dpr) file. Usually, the
options in this file are set from Project Options dialog.
Various tools in the IDE store data in files of other types. Desktop settings (.dsk)
files contain information about the arrangement of windows and other
configuration options; desktop settings can be project-specific or environment-
wide. These files have no direct effect on compilation.
Compiler-Generated Files
The first time you build an application or a package, the compiler produces a
compiled unit file (.dcu on Win32) for each new unit used in your project; all
the .dcu files in your project are then linked to create a single executable or
shared package. The first time you build a package, the compiler produces a file
for each new unit contained in the package, and then creates both a .dcp and
a package file. If you use the GD compiler switch, the linker generates a map file
and a .drc file; the .drc file, which contains string resources, can be compiled
into a resource file.
When you build a project, individual units are not recompiled unless their source
(.pas) files have changed since the last compilation, their .dcu/.dpu files cannot
be found, you explicitly tell the compiler to reprocess them, or the interface of
the unit depends on another unit which has been changed. In fact, it is not
necessary for a unit's source file to be present at all, as long as the compiler can
find the compiled unit file and that unit has no dependencies on other units that
have changed.
Example Programs
The examples that follow illustrate basic features of Delphi programming. The
examples show simple applications that would not normally be compiled from
the IDE; you can compile them from the command line.
Embarcadero Technologies 17
A Simple Console Application
The program below is a simple console application that you can compile and
run from the command prompt:
program Greeting;
{$APPTYPE CONSOLE}
var
MyMessage: string;
begin
MyMessage := 'Hello world!';
Writeln(MyMessage);
end.
The first line declares a program called Greeting. The {$APPTYPE CONSOLE}
directive tells the compiler that this is a console application, to be run from the
command line. The next line declares a variable called MyMessage, which holds
a string. (Delphi has genuine string data types.) The program then assigns the
string "Hello world!" to the variable MyMessage, and sends the contents of
MyMessage to the standard output using the Writeln procedure. (Writeln is
defined implicitly in the System unit, which the compiler automatically includes in
every application.)
You can type this program into a file called greeting.pas or greeting.dpr
and compile it by entering:
dcc32 greeting
Aside from its simplicity, this example differs in several important ways from
programs that you are likely to write with Embarcadero development tools. First,
it is a console application. Embarcadero development tools are most often used
to write applications with graphical interfaces; hence, you would not ordinarily
call Writeln. Moreover, the entire example program (save for Writeln) is in a single
file. In a typical GUI application, the program heading the first line of the
example would be placed in a separate project file that would not contain any
of the actual application logic, other than a few calls to routines defined in unit
files.
Embarcadero Technologies 18
A More Complicated Example
The next example shows a program that is divided into two files: a project file
and a unit file. The project file, which you can save as greeting.dpr, looks like
this:
program Greeting;
{$APPTYPE CONSOLE}
uses
Unit1;
begin
PrintMessage('Hello World!');
end.
The first line declares a program called greeting, which, once again, is a console
application. The uses Unit1; clause tells the compiler that the program greeting
depends on a unit called Unit1. Finally, the program calls the PrintMessage
procedure, passing to it the string Hello World! The PrintMessage procedure is
defined in Unit1. Here is the source code for Unit1, which must be saved in a file
called Unit1.pas:
unit Unit1;
interface
implementation
end.
Notice that PrintMessage is declared twice in Unit1. The first declaration, under
the reserved word interface, makes PrintMessage available to other modules
(such as greeting) that use Unit1. The second declaration, under the reserved
word implementation, actually defines PrintMessage.
You can now compile Greeting from the command line by entering
dcc32 greeting
Embarcadero Technologies 19
There is no need to include Unit1 as a command-line argument. When the
compiler processes greeting.dpr, it automatically looks for unit files that the
greeting program depends on. The resulting executable does the same thing as
our first example: it prints the message Hello world!
A VCL Application
Our next example is an application built using the Visual Component Library
(VCL) components in the IDE. This program uses automatically generated form
and resource files, so you won't be able to compile it from the source code
alone. But it illustrates important features of the Delphi Language. In addition to
multiple units, the program uses classes and objects.
The program includes a project file and two new unit files. First, the project file:
program Greeting;
uses
Forms, Unit1, Unit2;
begin
{ Calls to global Application instance }
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.CreateForm(TForm2, Form2);
Application.Run;
end.
Once again, our program is called greeting. It uses three units: Forms, which is
part of VCL; Unit1, which is associated with the application's main form (Form1);
and Unit2, which is associated with another form (Form2).
Embarcadero Technologies 20
Unit1 looks like this:
unit Unit1;
interface
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
uses Unit2;
{$R *.dfm}
end.
Embarcadero Technologies 21
Form2 is defined in Unit2:
unit Unit2;
interface
type
TForm2 = class(TForm)
Label1: TLabel;
CancelButton: TButton;
procedure CancelButtonClick(Sender: TObject);
end;
var
Form2: TForm2;
implementation
uses Unit1;
{$R *.dfm}
end.
Unit2 creates a class named TForm2 and an instance of this class, Form2. The
TForm2 class includes a button (CancelButton, an instance of Vcl.StdCtrls.TButton)
and a label (Label1, an instance of Vcl.StdCtrls.TLabel). You can not see this from
the source code, but Label1 displays a caption that reads Hello world! The
caption is defined in Form2's form file, Unit2.dfm.
When the greeting program starts, Form1 is displayed and Form2 is invisible. (By
default, only the first form created in the project file is visible at run time. This is
called the project's main form.) When the user presses the button on Form1, Form2
displays the Hello world! greeting. When the user presses the CancelButton or
the Close button on the title bar, Form2 closes.
Embarcadero Technologies 22
Programs and Units Index
This chapter provides a more detailed look at Delphi program organization.
Topics
o Programs and Units (Delphi)
Embarcadero Technologies 23
Programs and Units (Delphi)
This topic covers the overall structure of a Delphi application: the program
header, unit declaration syntax, and the uses clause.
Note: Strictly speaking, you need not explicitly use any units in a
project, but all programs automatically use the System unit and the
SysInit unit.
o a program heading,
The compiler, and hence the IDE, expect to find these three elements in a single
project (.dpr) file.
The following example shows the project source file for a program called
Editor. Since the program is called Editor, this project file is called
Editor.dpr.
Embarcadero Technologies 24
program Editor;
{$R *.res}
begin
Application.Title := 'Text Editor';
Application.CreateForm(TMainForm, MainForm);
Application.Run;
end.
The first line contains the program heading. The uses clause in this example
specifies a dependency on three additional units: Forms, REAbout, and REMain.
The $R compiler directive links the project's resource file into the program. Finally,
the block of statements between the begin and end keywords are executed
when the program runs. The project file, like all Delphi source files, ends with a
period (not a semicolon).
Delphi project files are usually short, since most of a program's logic resides in its
unit files. A Delphi project file typically contains only enough code to launch the
application's main window, and start the event processing loop. Project files are
generated and maintained automatically by the IDE, and it is seldom necessary
to edit them manually.
In RAD Studio, the program heading introduces its own namespace, which is
called the project default namespace.
The uses clause consists of the keyword uses, followed by a comma delimited list
of units the project file directly depends on.
The Block
The block contains a simple or structured statement that is executed when the
program runs. In most program files, the block consists of a compound statement
bracketed between the reserved words begin and end, whose component
Embarcadero Technologies 25
statements are simply method calls to the project's Application object. Most
projects have a global Application variable that holds an instance of
Vcl.Forms.TApplication, Web.WebBroker.TWebApplication, or
Vcl.SvcMgr.TServiceApplication. The block can also contain declarations of
constants, types, variables, procedures, and functions; these declarations must
precede the statement part of the block. Note that the end that represents the
end of the program source must be followed by a period (.):
begin
.
.
.
end.
A unit file begins with a unit heading, which is followed by the interface keyword.
Following the interface keyword, the uses clause specifies a list of unit
dependencies. Next comes the implementation section, followed by the
optional initialization, and finalization sections. A skeleton unit source file looks
like this:
unit Unit1;
interface
implementation
initialization
finalization
end.
The unit must conclude with the reserved word end followed by a period.
Embarcadero Technologies 26
The Unit Heading
The unit heading specifies the unit's name. It consists of the reserved word unit,
followed by a valid identifier, followed by a semicolon. For applications
developed using Embarcadero tools, the identifier must match the unit file
name. Thus, the unit heading:
unit MainForm;
would occur in a source file called MainForm.pas, and the file containing the
compiled unit would be MainForm.dcu. Unit names must be unique within a
project. Even if their unit files are in different directories, two units with the same
name cannot be used in a single program.
The interface declaration for a class must include declarations for all class
members: fields, properties, procedures, and functions.
The interface section can include its own uses clause, which must appear
immediately after the keyword interface.
Embarcadero Technologies 27
and functions that are private to the unit. That is, unlike the interface section,
entities declared in the implementation section are inaccessible to other units.
The implementation section can include its own uses clause, which must appear
immediately after the keyword implementation. The identifiers declared within
units specified in the implementation section are only available for use within the
implementation section itself. You cannot refer to such identifiers in the interface
section.
For units in the interface uses list, the initialization sections of the units used by a
client are executed in the order in which the units appear in the client's uses
clause.
The older "begin ... end." syntax still functions. Basically, the reserved word "begin"
can be used in place of initialization followed by zero or more execution
statements. Code using the older "begin ... end." syntax cannot specify a
finalization section. In this case, finalization is accomplished by providing a
procedure to the ExitProc variable. This method is not recommended for code
going forward, but you might see it used in older source code.
Embarcadero Technologies 28
Unit References and the Uses Clause
A uses clause lists units used by the program, library, or unit in which the clause
appears. A uses clause can occur in
Most project files contain a uses clause, as do the interface sections of most
units. The implementation section of a unit can contain its own uses clause as
well.
The System unit and the SysInit unit are used automatically by every application
and cannot be listed explicitly in the uses clause. (System implements routines for
file I/O, string handling, floating point operations, dynamic memory allocation,
and so forth.) Other standard library units, such as SysUtils, must be explicitly
included in the uses clause. In most cases, all necessary units are placed in the
uses clause by the IDE, as you add and remove units from your project.
Case Sensitivity: In unit declarations and uses clauses, unit names must match
the file names in case. In other contexts (such as qualified identifiers), unit names
are case insensitive. To avoid problems with unit references, refer to the unit
source file explicitly:
If such an explicit reference appears in the project file, other source files can
refer to the unit with a simple uses clause that does not need to match case:
uses Myunit;
uses
Forms,
Main;
In the uses clause of a program or library, any unit name may be followed by the
reserved word in and the name of a source file, with or without a directory path,
in single quotation marks; directory paths can be absolute or relative. Examples:
Embarcadero Technologies 29
uses
Windows, Messages, SysUtils,
Strings in 'C:\Classes\Strings.pas', Classes;
Use the keyword in after a unit name when you need to specify the unit's source
file. Since the IDE expects unit names to match the names of the source files in
which they reside, there is usually no reason to do this. Using in is necessary only
when the location of the source file is unclear, for example when:
o You have used a source file that is in a different directory from the project
file, and that directory is not in the compiler's search path.
o You are compiling a console application from the command line, and
you have named a unit with an identifier that doesn't match the name of
its source file.
The compiler also relies on the in ... construction to determine which units are
part of a project. Only units that appear in a project (.dpr) file's uses clause
followed by in and a file name are considered to be part of the project; other
units in the uses clause are used by the project without belonging to it. This
distinction has no effect on compilation, but it affects IDE tools like the Project
Manager.
In the uses clause of a unit, you cannot use in to tell the compiler where to find a
source file. Every unit must be in the compiler's search path. Moreover, unit
names must match the names of their source files.
A uses clause need include only units used directly by the program or unit in
which the clause appears. That is, if unit A references constants, types, variables,
procedures, or functions that are declared in unit B, then A must use B explicitly. If
B in turn references identifiers from unit C, then A is indirectly dependent on C; in
this case, C needn't be included in a uses clause in A, but the compiler must still
be able to find both B and C in order to process A.
Embarcadero Technologies 30
The following example illustrates indirect dependency:
program Prog;
uses Unit2;
const a = b;
// ...
unit Unit2;
interface
uses Unit1;
const b = c;
// ...
unit Unit1;
interface
const c = 1;
// ...
In this example, Prog depends directly on Unit2, which depends directly on Unit1.
Hence Prog is indirectly dependent on Unit1. Because Unit1 does not appear in
Prog's uses clause, identifiers declared in Unit1 are not available to Prog.
To compile a client module, the compiler needs to locate all units that the client
depends on, directly or indirectly. Unless the source code for these units has
changed, however, the compiler needs only their .dcu files, not their source
(.pas) files.
When a change is made in the interface section of a unit, other units that
depend on the change must be recompiled. But when changes are made only
in the implementation or other sections of a unit, dependent units don't have to
be recompiled. The compiler tracks these dependencies automatically and
recompiles units only when necessary.
Embarcadero Technologies 31
In the simplest case of two mutually dependent units, this means that the units
cannot list each other in their interface uses clauses. So the following example
leads to a compilation error:
unit Unit1;
interface
uses Unit2;
// ...
unit Unit2;
interface
uses Unit1;
// ...
However, the two units can legally reference each other if one of the references
is moved to the implementation section:
unit Unit1;
interface
uses Unit2;
// ...
unit Unit2;
interface
//...
implementation
uses Unit1;
// ...
To reduce the chance of circular references, it's a good idea to list units in the
implementation uses clause whenever possible. Only when identifiers from
another unit are used in the interface section is it necessary to list that unit in the
interface uses clause.
Embarcadero Technologies 32
For example, the class MyClass in MyNameSpace, is different from the class
MyClass in YourNamespace.
Declaring Namespaces
In RAD Studio, a project file (program, library, or package) implicitly introduces its
own namespace, called the project default namespace. A unit may be a
member of the project default namespace, or it may explicitly declare itself to
be a member of a different namespace. In either case, a unit declares its
namespace membership in its unit header. For example, consider the following
explicit namespace declaration:
unit MyCompany.MyWidgets.MyUnit;
First, notice that the parts of namespaces are separated by dots. Namespaces
do not introduce new symbols for the identifiers between the dots; the dots are
part of the unit name. The source file name for this example is
MyCompany.MyWidgets.MyUnit.pas, and the compiled output file name is
MyCompany.MyWidgets.MyUnit.dcu.
Second, notice that the dots imply the conceptual nesting, or containment, of
one namespace within another. The example above declares the unit MyUnit to
be a member of the MyWidgets namespace, which itself is contained in the
MyCompany namespace. Again, it should be noted that this containment is for
documentation purposes only.
A project default namespace declares a namespace for all of the units in the
project. Consider the following declarations:
Program MyCompany.Programs.MyProgram;
Library MyCompany.Libs.MyLibrary;
Package MyCompany.Packages.MyPackage;
These statements establish the project default namespace for the program,
library, and package, respectively. The namespace is determined by removing
the rightmost identifier (and dot) from the declaration.
A unit that omits an explicit namespace is called a generic unit. A generic unit
automatically becomes a member of the project default namespace. Given the
preceding program declaration, the following unit declaration would cause the
compiler to treat MyUnit as a member of the MyCompany.Programs
namespace.
Embarcadero Technologies 33
unit MyUnit;
The project default namespace does not affect the name of the Delphi source
file for a generic unit. In the preceding example, the Delphi source file name
would be MyUnit.pas. The same rule applies for the dcu file name. The resulting
dcu file in the current example would be MyUnit.dcu.
Searching Namespaces
A unit must declare the other units on which it depends. The compiler must
search these units for identifiers. For units in explicit namespaces the search
scope is already known, but for generic units, the compiler must establish a
namespace search scope.
Embarcadero Technologies 34
// Project file declarations...
program MyCompany.ProjectX.ProgramY;
Given this program example, the compiler would search namespaces in the
following order:
1. MyCompany.ProjectX.ProgramY
2. MyCompany.ProjectX
Note that if the current unit is generic (i.e. it does not have an explicit
namespace declaration in its unit statement), then resolution begins with the
project default namespace.
Using Namespaces
Delphi's uses clause brings a module into the context of the current unit. The uses
clause must either refer to a module by its fully qualified name (i.e. including the
full namespace specification), or by its generic name, thereby relying on the
namespace resolution mechanisms to locate the unit.
unit MyCompany.Libs.MyUnit1;
uses MyCompany.Libs.Unit2, // Fully qualified name.
UnitX; // Generic name.
Once a module has been brought into context, source code can refer to
identifiers within that module either by the unqualified name, or by the fully
qualified name (if necessary, to disambiguate identifiers with the same name in
different units). The following Writeln statements are equivalent:
uses MyCompany.Libs.Unit2;
begin
Writeln(MyCompany.Libs.Unit2.SomeString);
Writeln(SomeString);
end.
A fully qualified identifier must include the full namespace specification. In the
preceding example, it would be an error to refer to SomeString using only a
portion of the namespace:
Embarcadero Technologies 35
Writeln(Unit2.SomeString); // ERROR!
Writeln(Libs.Unit2.SomeString); // ERROR!
Writeln(MyCompany.Libs.Unit2.SomeString); // Correct.
Writeln(SomeString); // Correct.
This restriction also applies to the with-do statement. The following will produce a
compiler error:
with MyCompany.Libs do // ERROR!
Multi-unit Namespaces
Multiple units can belong to the same namespace, if the unit declarations refer
to the same namespace. For example, one can create two files, unit1.pas and
unit2.pas, with the following unit declarations:
// in file 'unit1.pas'
unit MyCompany.ProjectX.ProgramY.Unit1
// in file 'unit2.pas'
unit MyCompany.ProjectX.ProgramY.Unit2
A uses clause may refer to a namespace as well as individual units within that
namespace. In this case, a fully qualified expression referring to a symbol from a
specific unit listed in the uses clause may be referred to using the actual unit
name or the fully-qualified name (including namespace and unit name) for the
qualifier. The two forms of reference are identical and refer to the same symbol.
Embarcadero Technologies 36
Note: Explicitly using a unit in the uses clause will only work when
you are compiling from source or dcu files. If the namespace units
are compiled into an assembly and the assembly is referenced by
the project instead of the individual units, then the source code
that explicitly refers to a unit in the namespace will fail.
Topics
o Fundamental Syntactic Elements (Delphi)
o Expressions (Delphi)
Embarcadero Technologies 37
Fundamental Syntactic Elements (Delphi)
Fundamental syntactic elements, called tokens, combine to form expressions,
declarations, and statements. A statement describes an algorithmic action that
can be executed within a program. An expression is a syntactic unit that occurs
within a statement and denotes a value. A declaration defines an identifier
(such as the name of a function or variable) that can be used in expressions and
statements, and, where appropriate, allocates memory for the identifier.
This topic introduces the Delphi language character set, and describes the
syntax for declaring:
o Identifiers
o Numbers
o Character strings
o Labels
The RAD Studio compiler will accept a file encoded in UCS-2 or UCS-4 if the file
contains a byte order mark. The speed of compilation may be penalized by the
use for formats other than UTF-8, however. All characters in a UCS-4 encoded
source file must be representable in UCS-2 without surrogate pairs. UCS-2
encodings with surrogate pairs (including GB18030) are accepted only if the
codepage compiler option is specified.
Embarcadero Technologies 38
Tokens
On the simplest level, a program is a sequence of tokens delimited by
separators. A token is the smallest meaningful unit of text in a program. A
separator is either a blank or a comment. Strictly speaking, it is not always
necessary to place a separator between two tokens; for example, the code
fragment:
Size:=20;Price:=10;
Is perfectly legal. Convention and readability, however, dictate that we write this
in two lines, as:
Size := 20;
Price := 10;
Special Symbols
Special symbols are non-alphanumeric characters, or pairs of such characters,
that have fixed meanings. The following single characters are special symbols:
# $ & ' ( ) * + , - . / : ; < = > @ [ ] ^ { }
The following table shows pairs of symbols used in Delphi that have similar
meanings (the symbol pairs {} and (* *) are comment characters that are further
described in Comments and Compiler Directives):
Special Symbols
Similar Special Symbols
[ ] (. .)
{ } (* *)
The left bracket [ is similar to the character pair of left parenthesis and period (..
The right bracket ] is similar to the character pair of period and right
parenthesis .).
The left brace { is similar to the character pair of left parenthesis and asterisk (*.
Embarcadero Technologies 39
The right brace } is similar to the character pair of asterisk and right parenthesis *).
Note: %, ?, \, !, " (double quotation marks), _ (underscore), | (pipe), and ~ (tilde) are not
special symbols.
Identifiers
Identifiers denote constants, variables, fields, types, properties, procedures,
functions, programs, units, libraries, and packages. An identifier can be of any
length, but only the first 255 characters are significant. An identifier must begin
with an alphabetic character, a Unicode character, or an underscore (_) and
cannot contain spaces. Alphanumeric characters, Unicode characters, digits,
and underscores are allowed after the first character. Reserved words cannot be
used as identifiers. Since the Delphi Language is case-insensitive, an identifier like
CalculateValue could be written in any of these ways:
CalculateValue
calculateValue
calculatevalue
CALCULATEVALUE
Qualified Identifiers
When you use an identifier that has been declared in more than one place, it is
sometimes necessary to qualify the identifier. The syntax for a qualified identifier
is:
identifier1.identifier2
Where identifier1 qualifies identifier2. For example, if two units each declare a
variable called CurrentValue, you can specify that you want to access the
CurrentValue in Unit2 by writing:
Unit2.CurrentValue
Form1.Button1.Click
Embarcadero Technologies 40
Extended Identifiers
You might encounter identifiers (e.g. types, or methods in a class) having the
same name as a Delphi language reserved word. For example, a class might
have a method called begin. Delphi reserved words such as begin cannot be
used for an identifier name.
If you fully qualify the identifier, then there is no problem. For example, if you
want to use the Delphi reserved word type for an identifer name, you must use its
fully qualified name:
var TMyType.type
// Using a fully qualified name avoids ambiguity with {{Delphi}} language
keyword.
Reserved Words
The following reserved words cannot be redefined or used as identifiers.
Embarcadero Technologies 41
Delphi Reserved Words:
and end interface record var
destructor if or to
Note: In addition to the words in the preceding table, private, protected, public,
published, and automated act as reserved words within class type declarations, but are
otherwise treated as directives. The words at and on also have special meanings, and
should be treated as reserved words. The keywords of object are used to define method
pointers.
Directives
Delphi has more than one type of directive. One meaning for "directive" is a
word that is sensitive in specific locations within source code. This type of
directive has special meaning in the Delphi language, but, unlike a reserved
word, appears only in contexts where user-defined identifiers cannot occur.
Hence -- although it is inadvisable to do so -- you can define an identifier that
looks exactly like a directive.
Embarcadero Technologies 42
Directives:
absolute export12 name public stdcall
Note:
1. far, near, and resident are obsolete.
3. library is also a keyword when used as the first token in project source
code; it indicates a DLL target. Otherwise, it marks a symbol so that it
produces a library warning when used.
4. local was a Kylix directive and is ignored for Delphi for Win32.
5. sealed is a class directive with odd syntax: 'class sealed'. A sealed class
cannot be extended or derived (like final in C++).
7. package, when used as the first token, indicates a package target and
enables package syntax. requires and contains are directives only in
package syntax.
Embarcadero Technologies 43
9. reference indicates a reference to a function or procedure.
11. platform, deprecated, experimental, and library are hinting (or warning)
directives. These directives produce warnings at compile time.
12. assembler and export directives have no meaning. They exist only for the
backward compatibility.
Types of Directives
Delphi has two types of directives, including the context-sensitive type of
directive listed in the Directives table above.
procedure P; forward;
Or:
Or:
property Foo: Integer read FFoo write FFoo default 42;
The last type of directive is the official compiler directive, which is a switch or
option that affects the behavior of the compiler. A compiler directive is
surrounded by braces ({}) and begins with a dollar-sign ($), like this:
{$POINTERMATH ON}
{$D+} // DEBUGINFO ON
Like the other types of directives, compiler directives are not keywords. For a list
of the compiler directives, see the Delphi compiler directives list.
Numerals
Integer and real constants can be represented in decimal notation as
sequences of digits without commas or spaces, and prefixed with the + or -
operator to indicate sign. Values default to positive (so that, for example, 67258 is
Embarcadero Technologies 44
equivalent to +67258) and must be within the range of the largest predefined
real or integer type.
Numerals with decimal points or exponents denote reals, while other numerals
denote integers. When the character E or e occurs within a real, it means "times
ten to the power of". For example, 7E2 means 7 * 10^2, and 12.25e+6 and
12.25e6 both mean 12.25 * 10^6.
For more information about real and integer types, see About Data Types
(Delphi). For information about the data types of numerals, see Declared
Constants.
Labels
You can use either an identifier or a non-negative integer number as a label. The
Delphi compiler allows numeric labels from 0 to 4294967295 (uint32 range).
Labels are used in goto statements. For more information about goto statements
and labels, see Goto Statements in Declarations and Statements (Delphi).
Character Strings
A character string, also called a string literal or string constant, consists of a
quoted string, a control string, or a combination of quoted and control strings.
Separators can occur only within quoted strings.
For example:
'Embarcadero' { Embarcadero }
'You''ll see' { You'll see }
'アプリケーションを Unicode 対応にする'
'''' { ' }
'' { null string }
' ' { a space }
Embarcadero Technologies 45
A control string is a sequence of one or more control characters, each of which
consists of the # symbol followed by an unsigned integer constant from 0 to
65,535 (decimal) or from $0 to $FFFF (hexadecimal) in UTF-16 encoding, and
denotes the character corresponding to a specified code value. Each integer is
represented internally by 2 bytes in the string. This is useful for representing control
characters and multibyte characters. The control string:
#89#111#117
'You'
You can combine quoted strings with control strings to form larger character
strings. For example, you could use:
To put a carriage-return line-feed between 'Line 1' and 'Line 2'. However, you
cannot concatenate two quoted strings in this way, since a pair of sequential
apostrophes is interpreted as a single character. (To concatenate quoted strings,
use the + operator or simply combine them into a single quoted string.)
A character string is compatible with any string type and with the PChar type.
Since an AnsiString type may contain multibyte characters, a character string
with one character, single or multibyte, is compatible with any character type.
When extended syntax is enabled (with compiler directive {$X+}), a nonempty
character string of length n is compatible with zero-based arrays and packed
arrays of n characters. For more information, see About Data Types (Delphi).
Comments that are alike cannot be nested. For instance, (*{}*) will. This latter
form is useful for commenting out sections of code that also contain comments.
Here are some recommendations about how and when to use the three types of
comment characters:
Embarcadero Technologies 46
o Use the double-slash (//) for commenting out temporary changes made
during development. You can use the Code Editor convenient CTRL+/
(slash) mechanism to quickly insert the double-slash comment character
while you are working.
o Use the parenthesis-star "(*...*)" both for development comments and for
commenting out a block of code that contains other comments. This
comment character permits multiple lines of source, including other types
of comments, to be removed from consideration by the compiler.
o Use the braces ({}) for in-source documentation that you intend to remain
with the code.
A comment that contains a dollar sign ($) immediately after the opening { or (* is
a compiler directive. For example,
{$WARNINGS OFF}
in
in is a Delphi reserved word that may be used to:
Embarcadero Technologies 47
Expressions (Delphi)
This topic describes syntax rules of forming Delphi expressions.
o Operators
o Function calls
o Set constructors
o Indexes
o Typecasts
Expressions
An expression is a construction that returns a value. The following table shows
examples of Delphi expressions:
X variable
15 integer constant
InterestRate variable
X * Y product of X and Y
Z / (1 - Z) quotient of Z and (1 - Z)
X = 1.5 Boolean
C in Range1 Boolean
The simplest expressions are variables and constants (described in About Data
Embarcadero Technologies 48
Types (Delphi)). More complex expressions are built from simpler ones using
operators, function calls, set constructors, indexes, and typecasts.
Operators
Operators behave like predefined functions that are part of the Delphi
language. For example, the expression (X + Y) is built from the variables X and Y,
called operands, with the + operator; when X and Y represent integers or reals,
(X + Y) returns their sum. Operators include @, not, ^, *, /, div, mod, and, shl, shr,
as, +, -, or, xor, =, >, <, <>, <=, >=, in, and is.
The operators @, not, and ^ are unary (taking one operand). All other operators
are binary (taking two operands), except that + and - can function as either a
unary or binary operator. A unary operator always precedes its operand (for
example, -B), except for ^, which follows its operand (for example, P^). A binary
operator is placed between its operands (for example, A = 7).
Except for ^, is, and in, all operators can take operands of type Variant; for
details, see Variant Types (Delphi).
The sections that follow assume some familiarity with Delphi data types; for more
information, see About Data Types (Delphi).
Arithmetic Operators
Arithmetic operators, which take real or integer operands, include +, -, *, /, div,
and mod.
Embarcadero Technologies 49
Operator Operation Operand Types Result Type Example
Boolean Operators
The Boolean operators not, and, or, and xor take operands of any Boolean type
and return a value of type Boolean.
Boolean Operators:
Embarcadero Technologies 50
Operator Operation Operand Types Result Type Example
These operations are governed by standard rules of Boolean logic. For example,
an expression of the form x and y is True if and only if both x and y are True.
Embarcadero Technologies 51
Short-circuit evaluation also allows the use of constructions that might otherwise
result in illegal run-time operations. For example, the following code iterates
through the string S, up to the first comma.
In the case where S has no commas, the last iteration increments I to a value
which is greater than the length of S. When the while condition is next tested,
complete evaluation results in an attempt to read S[I], which could cause a
run-time error. Under short-circuit evaluation, in contrast, the second part of the
while condition (S[I] <> ',') is not evaluated after the first part fails.
Use the $B compiler directive to control evaluation mode. The default state is
{$B}, which enables short-circuit evaluation. To enable complete evaluation
locally, add the {$B+} directive to your code. You can also switch to complete
evaluation on a project-wide basis by selecting Complete Boolean Evaluation in
the Compiler Options dialog (all source units will need to be recompiled).
Z := X or Y;
Embarcadero Technologies 52
Operator Operation Operand Types Result Type Example
o If the operands of an and, or, or xor operation are both integers, the result
is of the predefined integer type with the smallest range that includes all
possible values of both types.
o The operations x shl y and x shr y shift the value of x to the left or right
by y bits, which (if x is an unsigned integer) is equivalent to multiplying or
dividing x by 2^y; the result is of the same type as x. For example, if N stores
the value 01101 (decimal 13), then N shl 1 returns 11010 (decimal 26).
Note that the value of y is interpreted modulo the size of the type of x.
Thus for example, if x is an integer, x shl 40 is interpreted as x shl 8
because an integer is 32 bits and 40 mod 32 is 8.
Example
If x is a negative integer, the shl and shr operations are made clear in the
following example:
var
x: integer;
y: string;
...
begin
x := -20;
x := x shr 1;
//As the number is shifted to the right by 1 bit, the sign bit's value
replaced is with 0 (all negative numbers have the sign bit set to 1).
y := IntToHex(x, 8);
writeln(y);
//Therefore, x is positive.
//Decimal value: 2147483638
//Hexadecimal value: 7FFFFFF6
//Binary value: 0111 1111 1111 1111 1111 1111 1111 0110
end.
Embarcadero Technologies 53
String Operators
The relational operators =, <>, <, >, <=, and >= all take string operands (see
Relational operators later in this section). The + operator concatenates two
strings.
String Operators:
o The operands for + can be strings, packed strings (packed arrays of type
Char), or characters. However, if one operand is of type WideChar, the
other operand must be a long string (UnicodeString, AnsiString, or
WideString).
Pointer Operators
o The relational operators <, >, <=, and >= can take operands of type
PAnsiChar and PWideChar (see Relational operators). The following
operators also take pointers as operands. For more information about
pointers, see Pointers and Pointer Types (Delphi) in About Data Types
(Delphi).
Character-pointer operators:
Embarcadero Technologies 54
Operator Operation Operand Types Result Type Example
The ^ operator dereferences a pointer. Its operand can be a pointer of any type
except the generic Pointer, which must be typecast before dereferencing.
P = Q is True just in case P and Q point to the same address; otherwise, P <> Q is
True.
You can use the + and - operators to increment and decrement the offset of a
character pointer. You can also use - to calculate the difference between the
offsets of two character pointers. The following rules apply:
P + Q is not defined.
Set Operators
The following operators take sets as operands.
Set Operators:
Embarcadero Technologies 55
Operator Operation Operand Types Result Type Example
Relational Operators
Relational operators are used to compare two operands. The operators =, <>, <=,
and >= also apply to sets.
Relational Operators:
Embarcadero Technologies 56
Result
Operator Operation Operand Types Example
Type
> greater-than simple, string, packed string, PChar Boolean Len > 0
<= less-than-or- simple, string, packed string, PChar Boolean Cnt <=
equal-to I
o Strings are compared according to the ordinal values that make up the
characters that make up the string. Character types are treated as strings
of length 1.
o Use the operators <, >, <=, and >= to compare PAnsiChar (and
PWideChar) operands only if the two pointers point within the same
character array.
o The operators = and <> can take operands of class and class-reference
types. With operands of a class type, = and <> are evaluated according
the rules that apply to pointers: C = D is True just in case C and D point to
the same instance object, and C <> D is True otherwise. With operands of
a class-reference type, C = D is True just in case C and D denote the same
class, and C <> D is True otherwise. This does not compare the data stored
in the classes. For more information about classes, see Classes and
Objects (Delphi).
Embarcadero Technologies 57
Class and Interface Operators
The operators as and is take classes and instance objects as operands; as
operates on interfaces as well. For more information, see Classes and Objects
(Delphi), Object Interfaces (Delphi) and Interface References (Delphi).
The @ Operator
The @ operator returns the address of a variable, or of a function, procedure, or
method; that is, @ constructs a pointer to its operand. For more information
about pointers, see "Pointers and Pointer Types" in About Data Types (Delphi). The
following rules apply to @.
@TMyClass.DoSomething
Operator Precedence
In complex expressions, rules of precedence determine the order in which
operations are performed.
Precedence of operators
Embarcadero Technologies 58
Operators Precedence
@ first (highest)
not
* second
/
div
mod
and
shl
shr
as
+ third
-
or
xor
= fourth (lowest)
<>
<
>
<=
>=
in
is
multiplies Y times Z, then adds X to the result; * is performed first, because is has a
higher precedence than +. But:
X - Y + Z
first subtracts Y from X, then adds Z to the result; - and + have the same
precedence, so the operation on the left is performed first.
Embarcadero Technologies 59
multiplies Z times the sum of X and Y.
Parentheses are sometimes needed in situations where, at first glance, they seem
not to be. For example, consider the expression:
X = Y or X = Z
(X = (Y or X)) = Z
Parentheses often make code easier to write and to read, even when they are,
strictly speaking, superfluous. Thus the first example could be written as:
X + (Y * Z)
Here the parentheses are unnecessary (to the compiler), but they spare both
programmer and reader from having to think about operator precedence.
Function Calls
Because functions return a value, function calls are expressions. For example, if
you have defined a function called Calc that takes two integer arguments and
returns an integer, then the function call Calc(24,47) is an integer expression. If I
and J are integer variables, then I + Calc(J,8) is also an integer expression.
Examples of function calls include:
Sum(A, 63)
Maximum(147, J)
Sin(X + Y)
Eof(F)
Volume(Radius, Height)
GetValue
TSomeObject.SomeMethod(I,J);
For more information about functions, see Procedures and Functions (Delphi).
Embarcadero Technologies 60
Set Constructors
A set constructor denotes a set-type value. For example:
[5, 6, 7, 8]
denotes the set whose members are 5, 6, 7, and 8. The set constructor:
[ 5..8 ]
where each item is either an expression denoting an ordinal of the set's base
type or a pair of such expressions with two dots (..) in between. When an item
has the form x..y, it is shorthand for all the ordinals in the range from x to y,
including y; but if x is greater than y, then x..y, the set [x..y], denotes nothing
and is the empty set. The set constructor [ ] denotes the empty set, while [x]
denotes the set whose only member is the value of x.
For more information about sets, see Structured Types (Delphi) in About Data
Types (Delphi).
Indexes
Strings, arrays, array properties, and pointers to strings or arrays can be indexed.
For example, if FileName is a string variable, the expression FileName[3] returns
the third character in the string denoted by FileName, while FileName[I + 1]
returns the character immediately after the one indexed by I. For information
about strings, see Data Types, Variables and Constants. For information about
arrays and array properties, see Arrays in Data Types, Variables, and Constants
and "Array Properties" in Properties (Delphi) page.
Embarcadero Technologies 61
Typecasts
It is sometimes useful to treat an expression as if it belonged to different type. A
typecast allows you to do this by, in effect, temporarily changing an expression's
type. For example, Integer('A') casts the character A as an integer.
typeIdentifier(expression)
Value Typecasts
In a value typecast, the type identifier and the cast expression must both be
ordinal or pointer types. Examples of value typecasts include:
Integer('A')
Char(48)
Boolean(0)
Color(2)
Longint(@Buffer)
The statement:
I := Integer('A');
Variable Typecasts
You can cast any variable to any type, provided their sizes are the same and
you do not mix integers with reals. (To convert numeric types, rely on standard
functions like Int and Trunc.) Examples of variable typecasts include:
Char(I)
Boolean(Count)
TSomeDefinedType(MyVariable)
Embarcadero Technologies 62
Variable typecasts can appear on either side of an assignment statement. Thus:
You can cast variables to a procedural type. For example, given the
declarations:
type
TByteRec = record
Lo, Hi: Byte;
end;
TWordRec = record
Low, High: Word;
end;
PByte = ^Byte;
var
B: Byte;
W: Word;
L: Longint;
P: Pointer;
begin
W := $1234;
B := TByteRec(W).Lo;
TByteRec(W).Hi := 0;
L := $1234567;
W := TWordRec(L).Low;
B := TByteRec(TWordRec(L).Low).Hi;
B := PByte(L)^;
end;
Embarcadero Technologies 63
In this example, TByteRec is used to access the low- and high-order bytes of a
word, and TWordRec to access the low- and high-order words of a long integer.
You could call the predefined functions Lo and Hi for the same purpose, but a
variable typecast has the advantage that it can be used on the left side of an
assignment statement.
For information about typecasting pointers, see Pointers and Pointer Types
(Delphi). For information about casting class and interface types, see "The as
Operator" in Class References and Interface References (Delphi).
Aside from the uses clause (and reserved words like implementation, which
demarcate parts of a unit), a program consists entirely of declarations and
statements, that are organized into blocks.
o Declarations
Declarations
The names of variables, constants, types, fields, properties, procedures, functions,
programs, units, libraries, and packages are called identifiers. (Numeric constants
like 26057 are not identifiers.) Identifiers must be declared before you can use
them; the only exceptions are a few predefined types, routines, and constants
that the compiler understands automatically, the variable Result when it occurs
inside a function block, and the variable Self when it occurs inside a method
implementation.
declares a variable called Size that holds an Extended (real) value, while:
declares a function called DoThis that takes two strings as arguments and returns
an integer. Each declaration ends with a semicolon. When you declare several
Embarcadero Technologies 64
variables, constants, types, or labels at the same time, you need only write the
appropriate reserved word once:
var
Size: Extended;
Quantity: Integer;
Description: string;
The syntax and placement of a declaration depend on the kind of identifier you
are defining. In general, declarations can occur only at the beginning of a block
or at the beginning of the interface or implementation section of a unit (after the
uses clause). Specific conventions for declaring variables, constants, types,
functions, and so forth are explained in the documentation for those topics.
Hinting Directives
The 'hint' directives platform, deprecated, and library may be appended to any
declaration. These directives will produce warnings at compile time. Hint
directives can be applied to type declarations, variable declarations, class,
interface, and structure declarations, field declarations within classes or records,
procedure, function, and method declarations, and unit declarations.
When a hint directive appears in a unit declaration, it means that the hint applies
to everything in the unit. For example, the Windows 3.1 style OleAuto.pas unit on
Windows is completely deprecated. Any reference to that unit or any symbol in
that unit produces a deprecation message.
The platform hinting directive on a symbol or unit indicates that it may not exist or
that the implementation may vary considerably on different platforms. The
library hinting directive on a symbol or unit indicates that the code may not exist
or the implementation may vary considerably on different library architectures.
The platform and library directives do not specify which platform or library. If your
goal is writing platform-independent code, you do not need to know which
platform a symbol is specific to; it is sufficient that the symbol be marked as
specific to some platform to let you know it may cause problems for your goal of
portability.
Embarcadero Technologies 65
In the case of a procedure or function declaration, the hint directive should be
separated from the rest of the declaration with a semicolon. Examples:
var
VersionNumber: Real library;
type
AppError = class(Exception)
...
end platform;
When source code is compiled in the {$HINTS ON} {$WARNINGS ON} state, each
reference to an identifier declared with one of these directives generates an
appropriate hint or warning. Use platform to mark items that are specific to a
particular operating environment (such as Windows), deprecated to indicate
that an item is obsolete or supported only for backward compatibility, and
library to flag dependencies on a particular library or component framework.
The Delphi compiler also recognizes the hinting directive experimental. You can
use this directive to designate units that are in an unstable development state.
The compiler will emit a warning when it builds an application that uses the unit.
For more information about the Delphi hinting directives, see warning directives
in method declarations. All the Delphi directives are listed in Directives.
Statements
Statements define algorithmic actions within a program. Simple statements like
assignments and procedure calls can combine to form loops, conditional
statements, and other structured statements.
Simple Statements
A simple statement does not contain any other statements. Simple statements
include assignments, calls to procedures and functions, and goto jumps.
Assignment Statements
An assignment statement has the form:
variable := expression
Embarcadero Technologies 66
be replaced with the name of the function being defined. See Procedures and
Functions (Delphi).) The := symbol is sometimes called the assignment operator.
An assignment statement replaces the current value of the variable with the
value of the expression. For example:
I := 3;
assigns the value 3 to the variable I. The variable reference on the left side of the
assignment can appear in the expression on the right. For example:
I := I + 1;
X := Y + Z;
Done := (I >= 1) and (I < 100);
Hue1 := [Blue, Succ(C)];
I := Sqr(J) - I * K;
Shortint(MyChar) := 122;
TByteRec(W).Hi := 0;
MyString[I] := 'A';
SomeArray[I + 1] := P^;
TMyObject.SomeProperty := True;
With extended syntax enabled ({$X+}), function calls such as calls to procedures
can be treated as statements in their own right:
MyFunction(X);
When you use a function call this way, its return value is discarded.
For more information about procedures and functions, see Procedures and
Functions (Delphi).
Goto Statements
A goto statement, which has the form:
Embarcadero Technologies 67
goto label
label: statement
A label can be any valid identifier or any numeral from 0 through 4294967295.
The label declaration, marked statement, and goto statement must belong to
the same block. (See Blocks and Scope, below.) Hence, it is not possible to jump
into or out of a procedure or function. Do not mark more than one statement in
a block with the same label.
For example:
label StartHere;
...
StartHere: Beep;
goto StartHere;
Additionally, it is not possible to jump into or out of a try - finally or try -except
statement.
Embarcadero Technologies 68
The goto statement is generally discouraged in structured programming. It is,
however, sometimes used as a way of exiting from nested loops, as in the
following example:
procedure FindFirstAnswer;
var X, Y, Z, Count: Integer;
label FoundAnAnswer;
begin
Count := SomeConstant;
for X := 1 to Count do
for Y := 1 to Count do
for Z := 1 to Count do
if ... { some condition holds on X, Y, and Z } then
goto FoundAnAnswer;
FoundAnAnswer:
... { Code to execute when an answer is found }
end;
Notice that we are using goto to jump out of a nested loop. Never jump into a
loop or other structured statement, because this can have unpredictable
effects.
Structured Statements
Structured statements are built from other statements. Use a structured statement
when you want to execute other statements sequentially, conditionally, or
repeatedly.
Embarcadero Technologies 69
Compound Statements
A compound statement is a sequence of other (simple or structured) statements
to be executed in the order in which they are written. The compound statement
is bracketed by the reserved words begin and end, and its constituent
statements are separated by semicolons. For example:
begin
Z := X;
X := Y;
X := Y;
end;
The last semicolon before end is optional. So this could have been written as:
begin
Z := X;
X := Y;
Y := Z
end;
You can write a compound statement that contains only a single constituent
statement; like parentheses in a complex term, begin and end sometimes serve
to disambiguate and to improve readability. You can also use an empty
compound statement to create a block that does nothing:
begin
end;
With Statements
A with statement is a shorthand for referencing the fields of a record or the fields,
properties, and methods of an object. The syntax of a with statement is:
Embarcadero Technologies 70
or:
type
TDate = record
Day: Integer;
Month: Integer;
Year: Integer;
end;
var
OrderDate: TDate;
or you could write the following code without using a with statement:
if OrderDate.Month = 12 then
begin
OrderDate.Month := 1;
OrderDate.Year := OrderDate.Year + 1;
end
else
OrderDate.Month := OrderDate.Month + 1;
Embarcadero Technologies 71
variable or method of the same name that you want to access from the with
statement, you need to prepend it with a qualifier, as in the following example:
with OrderDate do
begin
Year := Unit1.Year;
...
end;
When multiple objects or records appear after with, the entire statement is
treated like a series of nested with statements. Thus:
is equivalent to:
with obj1 do
with obj2 do
...
with objn do
// statement
Since a with statement requires a variable or a field to operate upon, using it with
properties can be tricky at times. A with statement expects variables it operates
on to be available by reference.
The most important things to note when you are using with:
o You can use with on read-only properties only for reading. Trying to modify
a field in the exposed record or object results in a compile-time error.
o Even though the property allows write access to the field, you still cannot
use with to modify its fields.
The following code exemplifies the problem in using the with statement on read-
only properties exposing a record. Assuming you have the following class:
TShape = class
private
FCenter: TPoint;
public
property Center: TPoint read FCenter;
end;
Embarcadero Technologies 72
where TPoint is a records declared as follows:
TPoint = record
X, Y: Integer;
end;
Normally, the Center property is read-only and does not allow you to modify the
value or the fields of FCenter field. In this case, using a with statement like the
following will fail with a compile-time error since Shape.Center is not a variable
and you cannot have a reference to it:
with Shape.Center do
begin
X := 100;
Y := 100;
end;
The tricky part when using the with statement comes for read/write properties.
We have changed the original TShape class to allow write access to its FCenter
field:
TShape = class
private
FCenter: TPoint;
public
property Center: TPoint read FCenter '''write FCenter''';
end;
Even though the Center property is not read-only, the same compile-time error is
emitted. The solution to this problem is to change code that looks like this:
with Shape.Center do
begin
X := 100;
Y := 100;
end;
with TempPoint do
begin
X := 100;
Y := 100;
end;
Embarcadero Technologies 73
If Statements
There are two forms of the if statement: if...then and the if...then...else. The syntax
of an if...then statement is:
The then and else clauses contain one statement each, but it can be a
structured statement. For example:
if J <> o then
begin
Result := I / J;
Count := Count + 1;
end
else if Count = Last then
Done := True
else
Exit;
Notice that a semicolon between the then clause and the word else is never
used. You can place a semicolon after an entire if statement to separate it from
the next statement in its block, but the then and else clauses require nothing
more than a space or carriage return between them. Placing a semicolon
immediately before else (in an if statement) is a common programming error.
Embarcadero Technologies 74
A special difficulty arises in connection with nested if statements. This happens
because some if statements have else clauses while others do not, but the
syntax for the two kinds of statement is otherwise the same. In a series of nested
conditionals where there are fewer else clauses than if statements, it may not
seem clear which else clauses are bound to which ifs. Consider a statement of
the form:
However, the compiler always parses in the first way. That is, in real code, the
statement:
is equivalent to:
The rule is that nested conditionals are parsed starting from the innermost
conditional, with each else bound to the nearest available if on its left. To force
the compiler to read our example in the second way, you have to write it
explicitly as:
Embarcadero Technologies 75
Case Statements
The case statement may provide a readable alternative to deeply nested if
conditionals. A case statement has the form:
case selectorExpression of
caseList1: statement1;
...
caseListn: statementn;
end
o A subrange having the form First..Last, where First and Last both satisfy the
criterion above and First is less than or equal to Last.
o A list having the form item1, ..., itemn, where each item satisfies one of the
criteria above.
case selectorExpression of
caseList1: statement1;
...
caselistn: statementn;
else
statements;
end
Embarcadero Technologies 76
The case statement
case I of
1..5: Caption := 'Low';
6..9: Caption := 'High';
0, 10..99: Caption := 'Out of range';
else
Caption := '';
end
if I in [1..5] then
Caption := 'Low';
else if I in [6..10] then
Caption := 'High';
else if (I = 0) or (I in [10..99]) then
Caption := 'Out of range'
else
Caption := '';
case Selection of
Done: Form1.Close;
Compute: calculateTotal(UnitCost, Quantity);
else
Beep;
end;
Control Loops
Loops allow you to execute a sequence of statements repeatedly, using a
control condition or variable to determine when the execution stops. Delphi has
three kinds of control loops: repeat statements, while statements, and for
statements.
You can use the standard Break and Continue procedures to control the flow of
a repeat, while, or for statement. Break terminates the statement in which it
occurs, while Continue begins executing the next iteration of the sequence.
Repeat Statements
The syntax of a repeat statement is:
repeat statement1; ...; statementn; until expression
Embarcadero Technologies 77
where expression returns a Boolean value. (The last semicolon before until is
optional.) The repeat statement executes its sequence of constituent statements
continually, testing expression after each iteration. When expression returns True,
the repeat statement terminates. The sequence is always executed at least
once, because expression is not evaluated until after the first iteration.
repeat
K := I mod J;
I := J;
J := K;
until J = 0;
repeat
Write('Enter a value (0..9): ');
Readln(I);
until (I >= 0) and (I <= 9);
While Statements
A while statement is similar to a repeat statement, except that the control
condition is evaluated before the first execution of the statement sequence.
Hence, if the condition is false, the statement sequence is never executed.
while I > 0 do
begin
if Odd(I) then Z := Z * X;
I := I div 2;
X := Sqr(X);
end;
Embarcadero Technologies 78
For Statements
A for statement, unlike a repeat or while statement, requires you to specify
explicitly the number of iterations you want the loop to go through. The syntax of
a for statement is:
for counter := initialValue to finalValue do statement
or:
for counter := initialValue downto finalValue do statement
where:
The for statement assigns the value of initialValue to counter, then executes
statement repeatedly, incrementing or decrementing counter after each
iteration. (The for...to syntax increments counter, while the for...downto syntax
decrements it.) When counter returns the same value as finalValue, statement is
executed once more and the for statement terminates. In other words,
statement is executed once for every value in the range from initialValue to
finalValue. If initialValue is equal to finalValue, statement is executed exactly
once. If initialValue is greater than finalValue in a for...to statement, or less than
finalValue in a for...downto statement, then statement is never executed. After
the for statement terminates (provided this was not forced by a Break or an Exit
procedure), the value of counter is undefined.
Warning: The iteration variable counter cannot be modified within the loop. This
includes assignment and passing the variable to a var parameter of a
procedure. Doing so results in a compile-time warning.
Embarcadero Technologies 79
For purposes of controlling the execution of the loop, the expressions initialValue
and finalValue are evaluated only once, before the loop begins. Hence, the
for...to statement is almost, but not quite, equivalent to this while construction:
begin
counter := initialValue;
while counter <= finalValue do
begin
... {statement};
counter := Succ(counter);
end;
end.
The difference between this construction and the for...to statement is that the
while loop reevaluates finalValue before each iteration. This can result in
noticeably slower performance if finalValue is a complex expression, and it also
means that changes to the value of finalValue within statement can affect the
execution of the loop.
for I := 2 to 63 do
if Data[I] > Max then
Max := Data[I];
for I := 1 to 10 do
for J := 1 to 10 do
begin
X := 0;
for K := 1 to 10 do
X := X + Mat1[I,K] * Mat2[K,J];
Mat[I,J] := X;
end;
Embarcadero Technologies 80
The type of the iteration variable Element must match the type held in the
container. With each iteration of the loop, the iteration variable holds the current
collection member. As with regular for-loops, the iteration variable must be
declared within the same block as the for statement.
type
TIntArray = array[0..9] of Integer;
TGenericIntArray = array of Integer;
var
IArray1: array[0..9] of Integer = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
IArray2: array[1..10] of Integer = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
IArray3: array[1..2] of TIntArray = ((11, 12, 13, 14, 15, 16, 17, 18, 19,
20),
(21, 22, 23, 24, 25, 26, 27, 28, 29,
30));
MultiDimTemp: TIntArray;
DynArray: TGenericIntArray;
I: Integer;
begin
for I in IArray1 do
begin
{ Do something with I... }
end;
for I in DynArray do
begin
{ Do something with I... }
end;
end.
Embarcadero Technologies 81
The following example demonstrates iteration over string expressions:
var
C: Char;
S1, S2: String;
Counter: Integer;
begin
S1 := 'Now is the time for all good men to come to the aid of their
country.';
S2 := ''''''';
for C in S1 do
S2 := S2 + C;
if S1 = S2 then
Writeln('SUCCESS #1')
else
Writeln('FAIL #1');
for AC in OS1 do
OS2 := OS2 + AC;
end.
Embarcadero Technologies 82
The following example demonstrates iteration over set expressions:
type
var
MySet: TMySet;
MyThing: TMyThing;
CharSet: TCharSet;
C: Char;
begin
CharSet := [#0..#255];
for C in CharSet do
begin
// Do something with C...
end;
end.
To use the for-in loop construct on a class or interface, the class or interface must
implement a prescribed collection pattern. A type that implements the
collection pattern must have the following attributes:
Embarcadero Technologies 83
The following code demonstrates iterating over an enumerable container in
Delphi.
type
TMyIntArray = array of Integer;
TMyContainerEnumerator = class;
TMyContainer = class
public
Values: TMyIntArray;
function GetEnumerator: TMyContainerEnumerator;
end;
TMyContainerEnumerator = class
Container : TMyContainer;
Index : Integer;
public
constructor Create(AContainer : TMyContainer);
function GetCurrent: Integer;
function MoveNext: Boolean;
property Current: Integer read GetCurrent;
end;
var
MyContainer : TMyContainer;
I : Integer;
Counter : Integer;
begin
MyContainer := TMyContainer.Create;
MyContainer.Values := TMyIntArray.Create(100, 200, 300);
Counter := 0;
for I in MyContainer do
Inc(Counter, I);
Embarcadero Technologies 84
Iteration Over Datasets Using For Statements
Delphi supports for-in syntax construction to iterate over datasets. The compiler
recognizes the following dataset iteration pattern:
The following code snippet iterates over a dataset in Delphi. This sample code
explains how to output the values of the Name column to a Memo control.
var
ds: TDataSet;
//
FQuery1.SQL.Text := 'SELECT Name FROM Table1';
Memo1.Lines.Clear;
for ds in FDQuery1 do
Memo1.Lines.Add(ds.FieldByName('Name').AsString);
The following code snippet illustrates how to use the TDataSet.View method to
enumerate a dataset.
var
ds: TDataSet;
//...
Memo1.Lines.Clear;
for ds in FDQuery1.View(dmAllowClone) do
Memo1.Lines.Add(ds.FieldByName('name').AsString);
o System.Classes.TList
o System.Classes.TCollection
o System.Classes.TStrings
o System.Classes.TInterfaceList
o System.Classes.TComponent
Embarcadero Technologies 85
o Vcl.Menus.TMenuItem
o Vcl.ActnList.TCustomActionList
o Vcl.ComCtrls.TListItems
o Vcl.ComCtrls.TTreeNodes
o Vcl.ComCtrls.TToolBar
o Data.DB.TFields
o Data.DB.TDataSet
Blocks
A block consists of a series of declarations followed by a compound statement.
All declarations must occur together at the beginning of the block. So the form
of a block is:
{declarations}
begin
{statements}
end
The declarations section can include, in any order, declarations for variables,
constants (including resource strings), types, procedures, functions, and labels. In
a program block, the declarations section can also include one or more exports
clauses (see Libraries and Packages (Delphi).)
the first line of the declaration is the function heading and all of the succeeding
lines make up the block. Ch, L, Source, and Dest are local variables; their
declarations apply only to the UpperCase function block and override, in this
Embarcadero Technologies 86
block only, any declarations of the same identifiers that may occur in the
program block or in the interface or implementation section of a unit.
Scope
An identifier such as a variable or function name can be used only within the
scope of its declaration. The location of a declaration determines its scope. An
identifier declared within the declaration of a program, function, or procedure
has a scope limited to the block in which it is declared. An identifier declared in
the interface section of a unit has a scope that includes any other units or
programs that use the unit where the declaration occurs. Identifiers with
narrower scope, especially identifiers declared in functions and procedures, are
sometimes called local, while identifiers with wider scope are called global.
the declaration section of a from the point where it is declared to the end of the
program, function, or procedure current block, including all blocks enclosed within
that scope.
the interface section of a unit from the point where it is declared to the end of the
unit, and to any other unit or program that uses that
unit. (See Programs and Units (Delphi).)
the implementation section of a from the point where it is declared to the end of the
unit, but not within the block of unit. The identifier is available to any function or
any function or procedure procedure in the unit, including the initialization and
finalization sections, if present.
the definition of a record type from the point of its declaration to the end of the
(that is, the identifier is the name record-type definition. (See "Records" in Structured
of a field in the record) Types (Delphi).)
the definition of a class (that is, from the point of its declaration to the end of the
the identifier is the name of a class-type definition, and also includes descendants
data field property or method in of the class and the blocks of all methods in the class
the class) and its descendants. (See Classes and Objects
(Delphi).)
Naming Conflicts
When one block encloses another, the former is called the outer block and the
latter, the inner block. If an identifier declared in an outer block is redeclared in
an inner block, the inner declaration takes precedence over the outer one and
determines the meaning of the identifier for the duration of the inner block. For
example, if you declare a variable called MaxValue in the interface section of a
unit, and then declare another variable with the same name in a function
declaration within that unit, any unqualified occurrences of MaxValue in the
Embarcadero Technologies 87
function block are governed by the second, local declaration. Similarly, a
function declared within another function creates a new, inner scope in which
identifiers used by the outer function can be redeclared locally.
The use of multiple units further complicates the definition of scope. Each unit
listed in a uses clause imposes a new scope that encloses the remaining units
used and the program or unit containing the uses clause. The first unit in a uses
clause represents the outermost scope and each succeeding unit represents a
new scope inside the previous one. If two or more units declare the same
identifier in their interface sections, an unqualified reference to the identifier
selects the declaration in the innermost scope, that is, in the unit where the
reference itself occurs, or, if that unit does not declare the identifier, in the last
unit in the uses clause that does declare the identifier.
The System and SysInit units are used automatically by every program or unit. The
declarations in System, along with the predefined types, routines, and constants
that the compiler understands automatically, always have the outermost scope.
You can override these rules of scope and bypass an inner declaration by using
a qualified identifier (see "Qualified Identifiers" in Fundamental Syntactic
Elements (Delphi)) or a with statement (see "With Statements" above.)
Topics
o About Data Types (Delphi)
o Variables (Delphi)
o Declared Constants
Embarcadero Technologies 88
About Data Types (Delphi)
This topic presents a high-level overview of Delphi data types.
A type is essentially a name for a kind of data. When you declare a variable you
must specify its type, which determines the set of values the variable can hold
and the operations that can be performed on it. Every expression returns data of
a particular type, as does every function. Most functions and procedures require
parameters of specific types.
o Some types are predefined (or built-in); the compiler recognizes these
automatically, without the need for a declaration. Almost all of the types
documented in this language reference are predefined. Other types are
created by declaration; these include user-defined types and the types
defined in the product libraries.
Embarcadero Technologies 89
The outline below shows the taxonomy of Delphi data types:
o simple
ordinal
integer
character
Boolean
enumerated
subrange
real
o string
o structured
set
array
record
file
class
class reference
interface
o pointer
o procedural
o Variant
o type identifier
The standard function SizeOf operates on all variables and type identifiers. It
returns an integer representing the amount of memory (in bytes) required to store
data of the specified type. For example:
Embarcadero Technologies 90
Type declarations are illustrated in the topics that follow. For general information
about type declarations, see Data Types, Variables, and Constants Index
(Delphi).
Ordinal Types
Ordinal types include integer, character, Boolean, enumerated, and subrange
types. An ordinal type defines an ordered set of values in which each value
except the first has a unique predecessor and each value except the last has a
unique successor. Further, each value has an ordinality, which determines the
ordering of the type. In most cases, if a value has ordinality n, its predecessor has
ordinality n-1 and its successor has ordinality n+1.
For integer types, the ordinality of a value is the value itself. Subrange types
maintain the ordinalities of their base types. For other ordinal types, by default
the first value has ordinality 0, the next value has ordinality 1, and so forth. The
declaration of an enumerated type can explicitly override this default.
Several predefined functions operate on ordinal values and type identifiers. The
most important of them are summarized below.
Predecessor of
Pred Ordinal expression
expression's value
Successor of
Succ Ordinal expression
expression's value
For example, High(Byte) returns 255 because the highest value of type Byte is
255, and Succ(2) returns 3 because 3 is the successor of 2.
Embarcadero Technologies 91
The standard procedures Inc and Dec increment and decrement the value of
an ordinal variable. For example, Inc(I) is equivalent to I := Succ(I) and, if I is
an integer variable, to I := I + 1.
Integer Types
An integer type represents a subset of the integral numbers.
32-bit
-2147483648..2147483647 Signed
platform (-231..2^31-1) Integer
32-bit
s
NativeInt
-
64-bit
9223372036854775808..92233720368547758 Signed
platform 07 Int64
64-bit
s (-263..263-1)
32-bit
0..4294967295 Unsigne Cardina
platform (0..232-1)
d 32-bit l
s
NativeUIn
t
64-bit
0..18446744073709551615 Unsigne
platform (0..264-1) UInt64
d 64-bit
s
Embarcadero Technologies 92
32-bit
platform
s and
-2147483648..2147483647 Signed
64-bit Integer
(-231..231-1) 32-bit
Windows
platform
s
LongInt
64-bit
POSIX -
platform 9223372036854775808..92233720368547758 Signed
Int64
s include 07 64-bit
iOS and (-263..263-1)
Linux
32-bit
platform
s and
0..4294967295 Unsigne Cardina
64-bit (0..232-1) d 32-bit l
Windows
platform
LongWor s
d
64-bit
POSIX
platform 0..18446744073709551615 Unsigne
UInt64
s include (0..264-1) d 64-bit
iOS and
Linux
Note: 32-bit platforms include 32-bit Windows, 32-bit macOS, 32-bit iOS, iOS
Simulator and Android.
Embarcadero Technologies 93
Type Range Format Alias
-9223372036854775808..9223372036854775807
Int64 (-263..263-1) Signed 64-bit
0..18446744073709551615
UInt64 (0..264-1) Unsigned 64-bit
...
J := Int64(I) + 1;
Embarcadero Technologies 94
When you increment the last value or decrement the first value of an integer
type, the result wraps around the beginning or end of the range. For example,
the ShortInt type has the range -128..127; hence, after execution of the code:
var
I: Shortint;
...
I := High(Shortint);
I := I + 1;
Character Types
The character types are Char, AnsiChar, WideChar, UCS2Char, and UCS4Char:
A string constant of length 1, such as 'A', can denote a character value. The
predefined function Chr returns the character value for any integer in the range
of WideChar; for example, Chr(65) returns the letter A.
AnsiChar and WideChar values, like integers, wrap around when decremented
or incremented past the beginning or end of their range (unless range-checking
is enabled). For example, after execution of the code:
var
Letter: AnsiChar;
I: Integer;
begin
Letter := High(Letter);
for I := 1 to 66 do Inc(Letter);
end;
Embarcadero Technologies 95
Letter has the value A (ASCII 65).
Boolean Types
The 4 predefined Boolean types are Boolean, ByteBool, WordBool, and LongBool.
Boolean is the preferred type. The others exist to provide compatibility with other
languages and operating system libraries.
Boolean values are denoted by the predefined constants True and False. The
following relationships hold:
Ord(False) = 0 Ord(False) = 0
The previous remarks refer to the ordinality of Boolean values, not to the values
themselves. In Delphi, Boolean expressions cannot be equated with integers or
reals. Hence, if X is an integer variable, the statement:
if X then ...;
Embarcadero Technologies 96
generates a compilation error. Casting the variable to a Boolean type is
unreliable, but each of the following alternatives will work.
Enumerated Types
An enumerated type defines an ordered set of values by simply listing identifiers
that denote these values. The values have no inherent meaning. To declare an
enumerated type, use the syntax:
type typeName = (val1, ...,valn)
where typeName and each val are valid identifiers. For example, the declaration:
defines an enumerated type called Suit, whose possible values are Club,
Diamond, Heart, and Spade, where Ord(Club) returns 0, Ord(Diamond) returns 1,
and so on.
When you declare an enumerated type, you are declaring each val to be a
constant of type typeName. If the val identifiers are used for another purpose
within the same scope, naming conflicts occur. For example, suppose you
declare the type:
type TSound = (Click, Clack, Clock)
Unfortunately, Click is also the name of a method defined for TControl and all of
the objects in VCL that descend from it. So if you are writing an application and
you create an event handler like:
procedure TForm1.DBGridEnter(Sender: TObject);
var
Thing: TSound;
begin
...
Thing := Click;
end;
you will get a compilation error; the compiler interprets Click within the scope of
the procedure as a reference to a Click method of a TForm. You can work
Embarcadero Technologies 97
around this by qualifying the identifier; thus, if TSound is declared in MyUnit, you
would use:
Thing := MyUnit.Click;
A better solution, however, is to choose constant names that are not likely to
conflict with other identifiers. Examples:
type
TSound = (tsClick, tsClack, tsClock);
TMyColor = (mcRed, mcBlue, mcGreen, mcYellow, mcOrange);
Answer = (ansYes, ansNo, ansMaybe)
You can use the (val1, ..., valn) construction directly in variable
declarations, as if it were a type name:
var MyCard: (Club, Diamond, Heart, Spade);
But if you declare MyCard this way, you cannot declare another variable within
the same scope using these constant identifiers. Thus:
var Card1: (Club, Diamond, Heart, Spade);
var Card2: (Club, Diamond, Heart, Spade);
type
Suit = (Club, Diamond, Heart, Spade);
var
Card1: Suit;
Card2: Suit;
Embarcadero Technologies 98
defines a type called Size whose possible values include Small, Medium, and
Large, where Ord(Small) returns 5, Ord(Medium) returns 10, and Ord(Large)
returns 15.
An enumerated type is, in effect, a subrange whose lowest and highest values
correspond to the lowest and highest ordinalities of the constants in the
declaration. In the previous example, the Size type has 11 possible values whose
ordinalities range from 5 to 15. (Hence the type array[Size] of Char represents
an array of 11 characters.) Only three of these values have names, but the
others are accessible through typecasts and through routines such as Pred, Succ,
Inc, and Dec. In the following example, "anonymous" values in the range of Size
are assigned to the variable X.
var
X: Size;
begin
X := Small; // Ord(X) = 5
X := Size(6); // Ord(X) = 6
Inc(X); // Ord(X) = 7
Any value that is not explicitly assigned an ordinality has the ordinality one
greater than that of the previous value in the list. If the first value is not assigned
an ordinality, its ordinality is 0. Hence, given the declaration:
SomeEnum has only two possible values: Ord(e1) returns 0, Ord(e2) returns 1, and
Ord(e3) also returns 1; because e2 and e3 have the same ordinality, they
represent the same value.
Scoped Enumerations
You can use scoped enumerations in Delphi code if you enable the
{$SCOPEDENUMS ON} compiler directive.
Embarcadero Technologies 99
the {$SCOPEDENUMS ON} directive are not added to the global scope. To use a
scoped enumeration identifier, you should qualify it with the name of the
enumeration type introducing this identifier.
For instance, let us define the following unit in the Unit1.pas file
unit Unit1;
interface
// {$SCOPEDENUMS ON} // clear comment from this directive
type
TMyEnum = (First, Second, Third);
implementation
end.
uses
SysUtils, Unit1 in 'Unit1.pas';
var
// First: Integer; // clear comment from this variable
Value: TMyEnum;
begin
try
Value := First;
// Value := TMyEnum.First;
// Value := unit1.First;
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
end.
First, Run (F9) on this code. The code runs successfully. This means that the First
identifier, used in the
Value := First;
enumeration type.
{$SCOPEDENUMS ON}
compiler directive in the unit1 unit. This directive enforces the TMyEnum
enumeration to be scoped. Execute Run. The E2003 Undeclared identifier 'First'
error is generated on the
Value := First;
line. It informs that the {$SCOPEDENUMS ON} compiler directive prevents the First
identifier, introduced in the scoped TMyEnum enumeration, to be added to the
global scope.
Value := TMyEnum.First;
version of the Value variable (and comment the first version of Value). Execute
Run. The program runs successfully. This means that the First identifier is known
in the TMyEnum scope.
// {$SCOPEDENUMS ON}
compiler directive in unit1. Then clear comment from the declaration of the
First variable
First: Integer;
variable. Now the code in the program Project1 looks like this:
var
First: Integer;
Value: TMyEnum;
begin
try
Value := First;
First: Integer;
line causes the E2010 Incompatible types - 'TMyEnum' and 'Integer' error. This
means that the naming conflict occurs between the global scope First
identifier introduced in the TMyEnum enumeration and the First variable. You
can work around this conflict by qualifying the First identifier with the unit1 unit
in which it is defined. For this, comment again the first version of Value variable
and clear comment from the third one:
Value := unit1.First;
Execute Run. The program runs successfully. That is, now the First identifier can
be qualified with the unit1 unit scope. But what happens if we again enable the
{$SCOPEDENUMS ON}
line. This means that {$SCOPEDENUMS ON} prevents adding the First
enumeration's identifier in the unit1 scope. Now the First identifier is added
only in the TMyEnum enumeration's scope. To check this, let us again use the
Value := TMyEnum.First;
version of the Value variable. Execute Run and the code succeeds.
Subrange Types
A subrange type represents a subset of the values in another ordinal type (called
the base type). Any construction of the form Low..High, where Low and High are
constant expressions of the same ordinal type and Low is less than High, identifies
a subrange type that includes all values between Low and High. For example, if
you declare the enumerated type:
type
TColors = (Red, Blue, Green, Yellow, Orange, Purple, White, Black);
You can use numeric constants and characters (string constants of length 1) to
define subrange types:
type
SomeNumbers = -128..127;
Caps = 'A'..'Z';
When you use numeric or character constants to define a subrange, the base
type is the smallest integer or character type that contains the specified range.
declares an integer variable whose value can be anywhere in the range from 1
through 500.
The ordinality of each value in a subrange is preserved from the base type. (In
the first example, if Color is a variable that holds the value Green, Ord(Color)
returns 2 regardless of whether Color is of type TColors or TMyColors.) Values do
not wrap around the beginning or end of a subrange, even if the base is an
integer or character type; incrementing or decrementing past the boundary of a
subrange simply converts the value to the base type. Hence, while:
Real Types
A real type defines a set of numbers that can be represented with the floating-
point notation. The table below gives the ranges and storage formats for the real
types on 64-bit and 32-bit platforms.
Real types
Significant Size in
Type Platform Approximate Positive Range
decimal digits bytes
64-bit Intel
Linux
32-bit Intel
Extended 3.37e-4932 .. 1.18e+4932 10-20 16
macOS
32-bit Intel iOS
Simulator
-9223372036854775807..
Comp all 9223372036854775807 10-20 8
(-263+1.. 263-1)
-922337203685477.5807..
Currency all 922337203685477.5807 10-20 8
The 6-byte Real48 type was called Real in earlier versions of Object Pascal. If you
are recompiling code that uses the older, 6-byte Real type in Delphi, you may
want to change it to Real48. You can also use the {$REALCOMPATIBILITY ON}
compiler directive to turn Real back into the 6-byte type.
o Extended offers greater precision on 32-bit platforms than other real types.
On 64-bit platforms Extended is an alias for a Double; that is, the size of the
Extended data type is 8 bytes. Thus you have less precision using an Extended on
64-bit platforms compared to 32-bit platforms, where Extended is 10 bytes.
Therefore, if your applications use the Extended data type and you rely on
precision for floating-point operations, this size difference might affect your data.
Be careful using Extended if you are creating data files to share across platforms.
For more information, see The Extended Data Type Is 2 Bytes Smaller on 64-bit
Windows Systems.
All the string types described in this topic are supported by Delphi compilers for
desktop platforms, but Delphi compilers for mobile platforms only support
UTF8String, RawByteString and the default string type (UnicodeString). Also, with
Delphi compilers for mobile platforms, strings are 0-based and immutable; to
manipulate strings, use the TStringHelper functions, which are provided for this
String types
Maximum Memory
Type Used for
length required
The reserved word string functions like a general string type identifier. For
example:
var S: string;
creates a variable S that holds a string. On the Win32 platform, the compiler
interprets string (when it appears without a bracketed number after it) as
UnicodeString.
On the Win32 platform, you can use the {$H-} directive to turn string into
ShortString. This is a potentially useful technique when using older 16-bit Delphi
code or Turbo Pascal code with your current programs.
Note that the keyword string is also used when declaring ShortString types of
specific lengths (see Short Strings, below).
You can index a string variable just as you would an array. If S is a non-
UnicodeString string variable and i, an integer expression, S[i] represents the ith
byte in S, which may not be the ith character or an entire character at all for a
multibyte character string (MBCS). Similarly, indexing a UnicodeString variable
results in an element that may not be an entire character. If the string contains
characters in the Basic Multilingual Plane (BMP), all characters are 2 bytes, so
indexing the string gets characters. However, if some characters are not in the
BMP, an indexed element may be a surrogate pair - not an entire character.
The standard function Length returns the number of elements in a string. As noted
above, the number of elements is not necessarily the number of characters. The
SetLength procedure adjusts the length of a string. Note that the SizeOf function
returns the number of bytes used to represent a variable or type. Note that
SizeOf returns the number of characters in a string only for a short string. SizeOf
For a short string or AnsiString, S[i] is of type AnsiChar. For a WideString, S[i] is of
type WideChar. For single-byte (Western) locales, MyString[2] := 'A'; assigns
the value A to the second character of MyString. The following code uses the
standard UpCase function to convert MyString to uppercase:
var I: Integer;
begin
I := Length(MyString);
while I > 0 do
begin
MyString[I] := UpCase(MyString[I]);
I := I - 1;
end;
end;
Be careful indexing strings in this way, since overwriting the end of a string can
cause access violations. Also, avoid passing string indexes as var parameters,
because this results in inefficient code.
You can assign the value of a string constant - or any other expression that
returns a string - to a variable. The length of the string changes dynamically when
the assignment is made. Examples:
Short Strings
A ShortString is 0 to 255 single-byte characters long. While the length of a
ShortString can change dynamically, its memory is a statically allocated 256
bytes; the first byte stores the length of the string, and the remaining 255 bytes
are available for characters. If S is a ShortString variable, Ord(S[0]), like
Length(S), returns the length of S; assigning a value to S[0], like calling
SetLength, changes the length of S. ShortString is maintained for backward
compatibility only.
Variables declared in this way allocate only as much memory as the type
requires - that is, the specified maximum length plus one byte. In our example,
MyString uses 101 bytes, as compared to 256 bytes for a variable of the
predefined ShortString type.
The standard functions High and Low operate on short-string type identifiers and
variables. High returns the maximum length of the short-string type, while Low
returns zero.
AnsiString
AnsiString represents a dynamically allocated string whose maximum length is
limited only by available memory.
o In UTF-8, for instance, characters may be one to 4 bytes. In UTF-8, the first
128 Unicode characters map to the US-ASCII characters.
The Win32 platform supports single-byte and multibyte character sets as well as
Unicode. The Windows operating system supports UTF-16.
The UnicodeString type has exactly the same structure as the AnsiString type.
UnicodeString data is encoded in UTF-16.
Since UnicodeString and AnsiString have the same structure, they function very
similarly. When a UnicodeString variable is empty, it uses no additional memory.
When it is not empty, it points to a dynamically allocated block of memory that
contains the string value, and the memory handling for this is transparent to the
user. UnicodeString variables are reference counted, and two or more of them
can reference the same value without consuming additional memory.
Delphi can also support Unicode characters and strings through the WideChar,
PWideChar, and WideString types.
For more information on using Unicode, see Unicode in RAD Studio and Enabling
Applications for Unicode.
WideString
The WideString type represents a dynamically allocated string of 16-bit Unicode
characters. In some respects it is similar to AnsiString. On Win32, WideString is
compatible with the COM BSTR type.
Indexing of WideString multibyte strings is not reliable, since S[i] represents the
ith element (not necessarily the ith character) in S.
For Delphi, Char and PChar types are WideChar and PWideChar types,
respectively.
Note:
WideString is not supported by the Delphi compilers for mobile platforms, but is
used by the Delphi compilers for desktop platforms.
type
TIdentifier = array[0..15] of Char;
TFileName = array[0..259] of Char;
TMemoText = array[0..1023] of WideChar;
With extended syntax enabled ({$X+}), you can assign a string constant to a
statically allocated zero-based character array. (Dynamic arrays won't work for
this purpose.) If you initialize an array constant with a string that is shorter than the
declared length of the array, the remaining characters are set to #0.
points P to an area of memory that contains the original constant string 'Hello
world!' This is equivalent to:
You can also pass string constants to any function that takes value or const
parameters of type PChar or PWideChar - for example StrUpper('Hello
world!'). As with assignments to a PChar, the compiler generates a null-
terminated copy of the string and gives the function a pointer to that copy.
Finally, you can initialize PChar or PWideChar constants with string literals, alone
or in a structured type. Examples:
const
Message: PChar = 'Program terminated';
Prompt: PChar = 'Enter values: ';
Digits: array[0..9] of PChar =
('Zero', 'One', 'Two', 'Three', 'Four', 'Five',
'Six', 'Seven', 'Eight', 'Nine');
Zero-based character arrays are compatible with PChar and PWideChar. When
you use a character array in place of a pointer value, the compiler converts the
array to a pointer constant whose value corresponds to the address of the first
element of the array. For example:
The StrUpper function illustrates the use of pointer indexing to iterate through a
null-terminated string:
function StrUpper(Dest, Source: PChar; MaxLen: Integer): PChar;
var
I: Integer;
begin
I := 0;
while (I < MaxLen) and (Source[I] <> #0) do
begin
Dest[I] := UpCase(Source[I]);
Inc(I);
end;
Dest[I] := #0;
Result := Dest;
end;
In a binary operation, if one operand is a string and the other a PChar, the PChar
operand is converted to a UnicodeString.
S := string(P1) + string(P2);
o You can also use Pointer(S) to cast a string to an untyped pointer. But if S
is empty, the typecast returns nil.
The string is unique - that is, has a reference count of one. To guarantee that the string is
unique, call the SetLength, SetString, or UniqueString procedures.
The string has not been modified since the typecast was made.
The characters modified are all within the string. Be careful not to use an out-of-range
index on the pointer.
The same rules apply when mixing WideString values with PWideChar values.
o Sets
o Records
o File types
You can, however, specify byte alignment by including the reserved word
packed when you declare a structured type. The packed word specifies
compressed data storage. Here is an example declaration:
Sets
A set is a collection of values of the same ordinal type. The values have no
inherent order, nor is it meaningful for a value to be included twice in a set.
set of baseType
Because of the size limitations for base types, set types are usually defined with
subranges. For example, the declarations:
type
TSomeInts = 1..250;
TIntSet = set of TSomeInts;
create a set type called TIntSet whose values are collections of integers in the
range from 1 to 250. You could accomplish the same thing with:
type TIntSet = set of 1..250;
You can also use the set of ... construction directly in variable declarations:
Note: For more information, see the following warning message: W1050 WideChar
reduced to byte char in set expressions (Delphi).
set of Byte
set of (Club, Diamond, Heart, Spade)
set of Char;
Arrays
An array represents an indexed collection of elements of the same type (called
the base type). Because each element has a unique index, arrays, unlike sets,
can meaningfully contain the same value more than once. Arrays can be
allocated statically or dynamically.
Static Arrays
Static array types are denoted by constructions of the form:
where each indexType is an ordinal type whose range does not exceed 2GB.
Since the indexTypes index the array, the number of elements an array can hold
is limited by the product of the sizes of the indexTypes. In practice, indexTypes
are usually integer subranges.
declares a variable called MyArray that holds an array of 100 character values.
Given this declaration, MyArray[3] denotes the third character in MyArray. If you
create a static array but don't assign values to all its elements, the unused
elements are still allocated and contain random data; they are like uninitialized
variables.
is equivalent to:
is equivalent to:
The standard functions Low and High operate on array type identifiers and
variables. They return the low and high bounds of the array's first index type. The
standard function Length returns the number of elements in the array's first
dimension.
Dynamic Arrays
Dynamic arrays do not have a fixed size or length. Instead, memory for a
dynamic array is reallocated when you assign a value to the array or pass it to
the SetLength procedure. Dynamic-array types are denoted by constructions of
the form:
array of baseType
For example:
var MyFlexibleArray: array of Real;
SetLength(MyFlexibleArray, 20);
type
TMyFlexibleArray = array of Integer;
begin
MyFlexibleArray := TMyFlexibleArray.Create(1, 2, 3 {...});
end;
which allocates memory for three elements and assigns each element the given
value.
procedure MyProc;
var
A: array of Integer;
begin
A := [1, 2, 3];
end;
Notice that unlike with an array constructor, an array constant can be applied to
unnamed dynamic array type directly. This syntax is specific to dynamic arrays;
applying this technique to other array types is likely to result in the constant being
interpreted as a set, leading to an incompatible types error at compile-time.
Dynamic-array variables are implicitly pointers and are managed by the same
reference-counting technique used for long strings. To deallocate a dynamic
array, assign nil to a variable that references the array or pass the variable to
Finalize; either of these methods disposes of the array, provided there are no
other references to it. Dynamic arrays are automatically released when their
reference-count drops to zero. Dynamic arrays of length 0 have the value nil. Do
not apply the dereference operator (^) to a dynamic-array variable or pass it to
the New or Dispose procedure.
the value of A[0] is 2. (If A and B were static arrays, A[0] would still be 1.)
var
A, B: array of Integer;
begin
SetLength(A, 1);
A[0] := 1;
B := Copy(A);
B[0] := 2; { B[0] <> A[0] }
end;
var
A, B: array of Integer;
begin
SetLength(A, 1);
SetLength(B, 1);
A[0] := 2;
B[0] := 2;
end;
SetLength(A, 20)
A := Copy(A, 0, 20)
Once a dynamic array has been allocated, you can pass it to the standard
functions Length, High, and Low. Length returns the number of elements in the
array, High returns the array's highest index (that is, Length - 1), and Low returns 0.
In the case of a zero-length array, High returns -1 (with the anomalous
consequence that High < Low).
This indicates that the function operates on all arrays of the specified base type,
regardless of their size, how they are indexed, or whether they are allocated
statically or dynamically.
You can create multidimensional dynamic arrays that are not rectangular. The
first step is to call SetLength, passing it parameters for the first n dimensions of the
array. For example:
var Ints: array of array of Integer;
SetLength(Ints,10);
allocates ten rows for Ints but no columns. Later, you can allocate the columns
one at a time (giving them different lengths); for example:
SetLength(Ints[2], 5);
makes the third column of Ints five integers long. At this point (even if the other
columns haven't been allocated) you can assign values to the third column - for
example, Ints[2,4] := 6.
The following example uses dynamic arrays (and the IntToStr function declared in
the SysUtils unit) to create a triangular matrix of strings.
var
A : array of array of string;
I, J : Integer;
begin
SetLength(A, 10);
for I := Low(A) to High(A) do
begin
SetLength(A[I], I);
for J := Low(A[I]) to High(A[I]) do
A[I,J] := IntToStr(I) + ',' + IntToStr(J) + ' ';
end;
end;
var
Int1: array[1..10] of Integer;
Int2: array[1..10] of Integer;
...
Int1 := Int2;
or:
var
A: array of integer;
B: TBytes = [1,2,3,4]; //Initialization can be done from declaration
begin
...
A:=[1,2,3]; // assignation using constant array
A:=A+[4,5]; // addition - A will become [1,2,3,4,5]
...
end;
var
A: array of integer;
begin
...
A:=[1,2,3,4];
Insert(5,A,2); // A will become [1,2,5,3,4]
...
end;
System.Delete
The Delete function eliminates elements from a dynamic array and returns the
modified array:
var
A: array of integer;
begin
...
A:=[1,2,3,4];
Delete(A,1,2); //A will become [1,4]
...
end;
System.Concat The Concat function can be used to put together two different
dynamic arrays:
Records (traditional)
A record (analogous to a structure in some languages) represents a
heterogeneous set of elements. Each element is called a field; the declaration of
a record type specifies a name and type for each field. The syntax of a record
type declaration is:
For example, the following declaration creates a record type called TDateRec.
Each TDateRec contains three fields: an integer value called Year, a value of an
enumerated type called Month, and another integer between 1 and 31 called
Day. The identifiers Year, Month, and Day are the field designators for TDateRec,
and they behave like variables. The TDateRec type declaration, however, does
not allocate any memory for the Year, Month, and Day fields; memory is
allocated when you instantiate the record, like this:
This variable declaration creates two instances of TDateRec, called Record1 and
Record2.
You can access the fields of a record by qualifying the field designators with the
record's name:
Record1.Year := 1904;
Record1.Month := Jun;
Record1.Day := 16;
Record2 := Record1;
Because the scope of a field designator is limited to the record in which it occurs,
you don't have to worry about naming conflicts between field designators and
other variables.
var S: record
Name: string;
Age: Integer;
end;
However, a declaration like this largely defeats the purpose of records, which is
to avoid repetitive coding of similar groups of variables. Moreover, separately
declared records of this kind will not be assignment-compatible, even if their
structures are identical.
To declare a record type with a variant part, use the following syntax:
type recordTypeName = record
fieldList1: type1;
...
fieldListn: typen;
case tag: ordinalType of
constantList1: (variant1);
...
constantListn: (variantn);
end;
The first part of the declaration - up to the reserved word case - is the same as
that of a standard record type. The remainder of the declaration - from case to
the optional final semicolon - is called the variant part. In the variant part,
o tag is optional and can be any valid identifier. If you omit tag, omit the
colon (:) after it as well.
fieldList1: type1;
...
fieldListn: typen;
Records with variant parts are complicated syntactically but deceptively simple
semantically. The variant part of a record contains several variants which share
the same space in memory. You can read or write to any field of any variant at
any time; but if you write to a field in one variant and then to a field in another
variant, you may be overwriting your own data. The tag, if there is one, functions
as an extra field (of type ordinalType) in the non-variant part of the record.
Variant parts have two purposes. First, suppose you want to create a record type
that has fields for different kinds of data, but you know that you will never need
to use all of the fields in a single record instance. For example:
type
TEmployee = record
FirstName, LastName: string[40];
BirthDate: TDate;
case Salaried: Boolean of
True: (AnnualSalary: Currency);
False: (HourlyWage: Currency);
end;
The idea here is that every employee has either a salary or an hourly wage, but
not both. So when you create an instance of TEmployee, there is no reason to
allocate enough memory for both fields. In this case, the only difference
between the variants is in the field names, but the fields could just as easily have
been of different types. Consider some more complicated examples:
type
TPerson = record
FirstName, LastName: string[40];
BirthDate: TDate;
case Citizen: Boolean of
True: (Birthplace: string[40]);
False: (Country: string[20];
EntryPort: string[20];
EntryDate, ExitDate: TDate);
end;
type
TShapeList = (Rectangle, Triangle, Circle, Ellipse, Other);
TFigure = record
case TShapeList of
Rectangle: (Height, Width: Real);
Triangle: (Side1, Side2, Angle: Real);
Circle: (Radius: Real);
Ellipse, Other: ();
end;
The second reason for variant parts is that they let you treat the same data as
belonging to different types, even in cases where the compiler would not allow a
typecast. For example, if you have a 64-bit Real as the first field in one variant
and a 32-bit Integer as the first field in another, you can assign a value to the
Real field and then read back the first 32 bits of it as the value of the Integer field
(passing it, say, to a function that requires integer parameters).
Records (advanced)
In addition to the traditional record types, the Delphi language allows more
complex and "class-like" record types. In addition to fields, records may have
properties and methods (including constructors), class properties, class methods,
class fields, and nested types. For more information on these subjects, see the
documentation on Classes and Objects (Delphi). Here is a sample record type
definition with some "class-like" functionality.
type
TMyRecord = record
type
TInnerColorType = Integer;
var
Red: Integer;
class var
Blue: Integer;
procedure printRed();
constructor Create(val: Integer);
property RedProperty: TInnerColorType read Red write Red;
class property BlueProp: TInnerColorType read Blue write Blue;
end;
procedure TMyRecord.printRed;
begin
Writeln('Red: ', Red);
end;
Though records can now share much of the functionality of classes, there are
some important differences between classes and records.
o Virtual methods (those specified with the virtual, dynamic, and message
keywords) cannot be used in record types.
where fileTypeName is any valid identifier and type is a fixed-size type. Pointer
types - whether implicit or explicit - are not allowed, so a file cannot contain
dynamic arrays, long strings, classes, objects, pointers, variants, other files, or
structured types that contain any of these.
For example:
type
PhoneEntry = record
FirstName, LastName: string[20];
PhoneNumber: string[15];
Listed: Boolean;
end;
PhoneList = file of PhoneEntry;
For more information, see "Untyped Files" in Standard Routines and Input-Output.
Code Samples
o ComplexNumbers Sample (Records)
Pointers are typed to indicate the kind of data stored at the addresses they hold.
The general-purpose Pointer type can represent a pointer to any data, while
more specialized pointer types reference only specific types of data. The PByte
type is used for any byte data that is not character data.
Overview of pointers
To see how pointers work, look at the following example:
1 var
2 X, Y: Integer; // X and Y are Integer variables
3 P: ^Integer; // P points to an Integer
4 begin
5 X := 17; // assign a value to X
6 P := @X; // assign the address of X to P
7 Y := P^; // dereference P; assign the result to Y
8 end;
The @ operator, which is used here to take the address of a variable, also
operates on functions and procedures. For more information, see The @
Operator and Procedural Types in Statements and Expressions.
The caret symbol ^ has two purposes, both of which are illustrated in our
example. When it appears before a type identifier:
the caret symbol denotes a type that represents pointers to variables of type
typeName.
pointer^
the caret dereferences the pointer; that is, it returns the value stored at the
memory address held by the pointer.
This example might seem like a roundabout way of copying the value of one
variable to another - something that we could have accomplished with a simple
assignment statement. But pointers are useful for several reasons. First,
understanding pointers will help you to understand the Delphi language, since
pointers often operate behind the scenes in code where they don't appear
explicitly. Any data type that requires large, dynamically allocated blocks of
memory uses pointers. Long-string variables, for instance, are implicitly pointers,
as are class instance variables. Moreover, some advanced programming
techniques require the use of pointers.
Finally, pointers are sometimes the only way to circumvent Delphi's strict data
typing. By referencing a variable with an all-purpose Pointer, casting the Pointer
to a more specific type, and then dereferencing it, you can treat the data
stored by any variable as if it belonged to any type. For example, the following
code assigns data stored in a real variable to an integer variable:
type
PInteger = ^Integer;
var
R: Single;
I: Integer;
P: Pointer;
PI: PInteger;
begin
...
P := @R;
PI := PInteger(P);
I := PI^;
end;
Of course, reals and integers are stored in different formats. This assignment
simply copies raw binary data from R to I, without converting it.
The reserved word nil is a special constant that can be assigned to any pointer.
When nil is assigned to a pointer, the pointer doesn't reference anything.
With extended syntax enabled, you can omit the caret when referring to a
pointer, as in the following example:
{$X+}
type
PMyRec = ^TMyRec;
TMyRec = record
Data: Integer;
end;
var
MyRec: PMyRec;
begin
New(MyRec);
MyRec.Data := 42; {#1}
end.
When extended syntax is not enabled, the line marked {#1} would typically be
expressed as:
MyRec^.Data := 42;
Pointer Types
You can declare a pointer to any type, using the syntax:
When you define a record or other data type, it might be useful to also define a
pointer to that type. This makes it easy to manipulate instances of the type
without copying large blocks of memory.
Note: You can declare a pointer type before you declare the type
it points to.
Character Pointers
The fundamental types PAnsiChar and PWideChar represent pointers to AnsiChar
and WideChar values, respectively. The generic PChar represents a pointer to a
Char (that is, in its current implementation, to a WideChar). These character
pointers are used to manipulate null-terminated strings. (See "Working with null-
terminated strings" in String Types (Delphi).)
Byte Pointer
The fundamental type PByte represents a pointer to any byte data that is not
character data. This type is declared with the {$POINTERMATH ON} compiler
directive:
Type-checked Pointers
The $T compiler directive controls the types of pointer values generated by the @
operator. This directive takes the form of:
{$T+} or {$T-}
In the {$T-} state, the result type of the @ operator is always an untyped pointer
that is compatible with all other pointer types. When @ is applied to a variable
reference in the {$T+} state, the type of the result is ^T, where T is compatible only
with pointers to the type of the variable.
PString UnicodeString
PAnsiString AnsiString
PInteger Integer
POleVariant OleVariant
PShortString ShortString. Useful when porting legacy code that uses the
old PString type.
PVariant Variant
PWideString WideString
This topic does not refer to the newer type of procedural type used with
anonymous methods, that is, a "reference to a procedure". See Anonymous
Methods in Delphi.
If you take any procedure or function heading and remove the identifier after
the word procedure or function, what is left is the right part of a procedural type
declaration. You can use such type names directly in variable declarations (as in
the previous example) or to declare new types:
type
TIntegerFunction = function: Integer;
TProcedure = procedure;
TStrProc = procedure(const S: string);
TMathFunc = function(X: Double): Double;
var
F: TIntegerFunction; // F is a parameterless function that returns an
integer
Proc: TProcedure; // Proc is a parameterless procedure
SP: TStrProc; // SP is a procedure that takes a string parameter
M: TMathFunc; // M is a function that takes a Double (real)
// parameter and returns a Double
Method Pointers
The variables shown in the previous example are all procedure pointers - that is,
pointers to the address of a procedure or function. If you want to reference a
method of an instance object (see Classes and Objects (Delphi)), you need to
add the words of object to the procedural type name. For example:
type
TMethod = procedure of object;
TNotifyEvent = procedure(Sender: TObject) of object;
OnClick := MainForm.ButtonClick;
Procedure pointer types are always incompatible with method pointer types. The
value nil can be assigned to any procedural type.
var
F: function(X: Integer): Integer;
I: Integer;
function SomeFunction(X: Integer): Integer;
...
F := SomeFunction; // assign SomeFunction to F
I := F(4); // call function; assign result to I
In assignment statements, the type of the variable on the left determines the
interpretation of procedure or method pointers on the right. For example:
var
F, G: function: Integer;
I: Integer;
function SomeFunction: Integer;
...
F := SomeFunction; // assign SomeFunction to F
G := F; // copy F to G
I := G; // call function; assign result to I
The first statement assigns a procedural value to F. The second statement copies
that value to another variable. The third statement makes a call to the
referenced function and assigns the result to I. Because I is an integer variable,
not a procedural one, the last assignment actually calls the function (which
returns an integer).
In this case, the occurrence of F results in a function call; the compiler calls the
function pointed to by F, then calls the function MyFunction, then compares the
results. The rule is that whenever a procedural variable occurs within an
expression, it represents a call to the referenced procedure or function. In a case
where F references a procedure (which doesn't return a value), or where F
references a function that requires parameters, the previous statement causes a
compilation error. To compare the procedural value of F with MyFunction, use:
if @F = @MyFunction then ...;
To get the memory address of a procedural variable (rather than the address
stored in it), use @@. For example, @@F returns the address of F.
Any procedural variable can hold the value nil, which means that it points to
nothing. But attempting to call a nil-valued procedural variable is an error. To test
whether a procedural variable is assigned, use the standard function Assigned:
Variants Overview
Sometimes it is necessary to manipulate data whose type varies or cannot be
determined at compile time. In these cases, one option is to use variables and
parameters of type Variant, which represent values that can change type at run
time. Variants offer greater flexibility but consume more memory than regular
variables, and operations on them are slower than on statically bound types.
Moreover, illicit operations on variants often result in run-time errors, where similar
mistakes with regular variables would have been caught at compile time. You
can also create custom variant types.
By default, Variants can hold values of any type except records, sets, static
arrays, files, classes, class references, and pointers. In other words, variants can
hold anything but structured types and pointers. They can hold interfaces, whose
methods and properties can be accessed through them. (See Object Interfaces
(Delphi).) They can hold dynamic arrays, and they can hold a special kind of
static array called a variant array. (See "Variant arrays" later in this chapter.)
Variants can mix with other variants and with integer, real, string, and Boolean
values in expressions and assignments; the compiler automatically performs type
conversions.
Variants that contain strings cannot be indexed. That is, if V is a variant that holds
a string value, the construction V[1] causes a run-time error.
The standard function VarType returns a variant's type code. The varTypeMask
constant is a bit mask used to extract the code from VarType's return value, so
that, for example,
returns True if V contains a Double or an array of Double. (The mask simply hides
the first bit, which indicates whether the variant holds an array.) The TVarData
record type defined in the System unit can be used to typecast variants and
gain access to their internal representation.
var
V1, V2, V3, V4, V5: Variant;
I: Integer;
D: Double;
S: string;
begin
V1 := 1; { integer value }
V2 := 1234.5678; { real value }
V3 := 'Hello world!'; { string value }
V4 := '1000'; { string value }
V5 := V1 + V2 + V4; { real value 2235.5678}
I := V1; { I = 1 (integer value) }
D := V2; { D = 1234.5678 (real value) }
S := V3; { S = 'Hello world!' (string value) }
I := V4; { I = 1000 (integer value) }
S := V5; { S = '2235.5678' (string value) }
end;
Boole False = 0, True: all False = 0, True = 1 False = 'False', True = False = False, True
an bits set to 1 (-1 if 'True' by default; = True
Integer, 255 if casing depends on
Byte, etc.) global variable
System.Variants.Bool
eanToStringRule.
Out-of-range assignments often result in the target variable getting the highest
value in its range. Invalid variant operations, assignments or casts raise an
Variants.EVariantError exception or an exception class descending from
Variants.EVariantError.
Variants in Expressions
All operators except ^, is, and in take variant operands. Except for comparisons,
which always return a Boolean result, any operation on a variant value returns a
variant result. If an expression combines variants with statically-typed values, the
statically-typed values are automatically converted to variants.
This is not true for comparisons, where any operation on a Null variant produces
a Null variant. For example:
V := Null + 3;
In this example, the else part of the if statement will be executed. This behavior
can be changed by setting the NullEqualityRule and NullMagnitudeRule global
variables.
Variant Arrays
You cannot assign an ordinary static array to a variant. Instead, create a variant
array by calling either of the standard functions VarArrayCreate or VarArrayOf.
For example:
V: Variant;
...
V := VarArrayCreate([0,9], varInteger);
creates a variant array of integers (of length 10) and assigns it to the variant V.
The array can be indexed using V[0], V[1], and so forth, but it is not possible to
pass a variant array element as a var parameter. Variant arrays are always
indexed with integers.
Variants can hold variant arrays of different sizes, dimensions, and base types.
The elements of a variant array can be of any type allowed in variants except
ShortString and AnsiString, and if the base type of the array is Variant, its elements
can even be heterogeneous. Use the VarArrayRedim function to resize a variant
array. Other standard routines that operate on variant arrays include
VarArrayDimCount, VarArrayLowBound, VarArrayHighBound, VarArrayRef,
VarArrayLock, and VarArrayUnlock.
OleVariant
The main difference between Variant and OleVariant is that Variant can contain
data types that only the current application knows what to do with. OleVariant
can only contain the data types defined as compatible with OLE Automation,
which means the data types that can be passed between programs or across
the network without worrying about whether the other end will know how to
handle the data.
When you assign a Variant that contains custom data (such as a Delphi string, or
one of the new custom variant types) to an OleVariant, the runtime library tries to
convert the Variant into one of the OleVariant standard data types (such as a
Delphi string converts to an OLE BSTR string). For example, if a variant containing
an AnsiString is assigned to an OleVariant, the AnsiString becomes a WideString.
The same is true when passing a Variant to an OleVariant function parameter.
o Type identity
o Type compatibility
o Assignment compatibility
type
T1 = Integer;
T2 = T1;
T3 = Integer;
T4 = T2;
T1, T2, T3, T4, and Integer all denote the same type. To create distinct types,
repeat the word type in the declaration. For example:
create two distinct types, TS1 and TS2. Similarly, the variable declarations:
var
S1: string[10];
S2: string[10];
create two variables of distinct types. To create variables of the same type, use:
var S1, S2: string[10];
or:
Type Compatibility
Every type is compatible with itself. Two distinct types are compatible if they
satisfy at least one of the following conditions.
o One is a string type and the other is a string, packed-string, or Char type.
o One type is Variant and the other is an integer, real, string, character, or
Boolean type.
o Both are class, class-reference, or interface types, and one type is derived
from the other.
o One type is Pointer (an untyped pointer) and the other is any pointer type.
o Both types are (typed) pointers to the same type and the {$T+} compiler
directive is in effect.
o Both are procedural types with the same result type, the same number of
parameters, and type-identity between parameters in corresponding
positions.
Assignment Compatibility
Assignment-compatibility is not a symmetric relation. An expression of type T2
can be assigned to a variable of type T1 if the value of the expression falls in the
range of T1 and at least one of the following conditions is satisfied:
o T1 and T2 are of the same type, and it is not a file type or structured type
that contains a file type at any level.
A type identifier's scope doesn't include the type declaration itself (except for
pointer types). So you cannot, for example, define a record type that uses itself
recursively.
When you declare a type that is identical to an existing type, the compiler treats
the new type identifier as an alias for the old one. Thus, given the declarations:
X and Y are of the same type; at run time, there is no way to distinguish TValue
from Real. This is usually of little consequence, but if your purpose in defining a
new type is to utilize runtime type information, for example, to associate a
property editor with properties of a particular type - the distinction between
'different name' and 'different type' becomes important. In this case, use the
syntax:
For example:
type
TMyType = type Integer;
procedure p(var t:TMyType);
begin
end;
procedure x;
var
m: TMyType;
i: Integer;
begin
p(m); // Works
p(i); // Error! Types of formal and actual must be identical.
end;
Variables (Delphi)
A variable is an identifier whose value can change at run time. Put differently, a
variable is a name for a location in memory; you can use the name to read or
write to the memory location. Variables are like containers for data, and,
because they are typed, they tell the compiler how to interpret the data they
hold.
Declaring Variables
The basic syntax for a variable declaration is:
var identifierList:type;
var I: Integer;
var X, Y: Real;
var
X, Y, Z: Double;
I, J, K: Integer;
Digit: 0..9;
Okay: Boolean;
When you declare a variable, you are allocating memory which is freed
automatically when the variable is no longer used. In particular, local variables
exist only until the program exits from the function or procedure in which they are
declared. For more information about variables and memory management, see
Memory Management.
Absolute Addresses
You can create a new variable that resides at the same address as another
variable. To do so, put the directive absolute after the type name in the
declaration of the new variable, followed by the name of an existing (previously
declared) variable. For example:
var
Str: string[32];
StrLen: Byte absolute Str;
Dynamic Variables
You can create dynamic variables by calling the GetMem or New procedure.
Such variables are allocated on the heap and are not managed automatically.
Once you create one, it is your responsibility ultimately to free the variable's
memory; use FreeMem to destroy variables created by GetMem and Dispose to
destroy variables created by New. Other standard routines that operate on
dynamic variables include ReallocMem, AllocMem, Initialize, Finalize, StrAlloc,
and StrDispose.
Long strings, wide strings, dynamic arrays, variants, and interfaces are also heap-
allocated dynamic variables, but their memory is managed automatically.
Thread-local Variables
Thread-local (or thread) variables are used in multithreaded applications. A
thread-local variable is like a global variable, except that each thread of
execution gets its own private copy of the variable, which cannot be accessed
from other threads. Thread-local variables are declared with threadvar instead of
var. For example:
threadvar X: Integer;
Thread-variable declarations:
Dynamic variables that are ordinarily managed by the compiler (long strings,
wide strings, dynamic arrays, variants, and interfaces) can be declared with
threadvar, but the compiler does not automatically free the heap-allocated
memory created by each thread of execution. If you use these data types in
thread variables, it is your responsibility to dispose of their memory from within the
thread, before the thread terminates. For example:
threadvar S: AnsiString;
S := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
...
S := ''; // free the memory used by S
Declared Constants
Several different language constructions are referred to as 'constants'. There are
numeric constants (also called numerals) like 17, and string constants (also called
character strings or string literals) like 'Hello world!'. Every enumerated type
defines constants that represent the values of that type. There are predefined
constants like True, False, and nil. Finally, there are constants that, like variables,
are created individually by declaration.
Declared constants are either true constants or typed constants. These two kinds
of constant are superficially similar, but they are governed by different rules and
used for different purposes.
True Constants
A true constant is a declared identifier whose value cannot change. For
example:
declares a constant called MaxValue that returns the integer 237. The syntax for
declaring a true constant is:
If constantExpression returns an ordinal value, you can specify the type of the
declared constant using a value typecast. For example:
declares a constant called MyNumber, of type Int64, that returns the integer 17.
Otherwise, the type of the declared constant is the type of the
constantExpression.
Byte UInt8
0 0
$FF 255
Word UInt16
0 0
$FFFF 65535
Cardinal UInt32,
0 0
$FFFFFFFF 4294967295 FixedUInt
UInt64
0 0
$FFFFFFFFFFFFFFFF 18446744073709551615
ShortInt Int8
-$80 -128
$7F 127
SmallInt Int16
-$8000 -32768
$7FFF 32767
Int64
-$8000000000000000 -9223372036854775808
$7FFFFFFFFFFFFFFF 9223372036854775807
NativeInt Integer
-$80000000 -2147483648
$7FFFFFFF 2147483647
NativeUInt Cardinal
0 0
$FFFFFFFF 4294967295
NativeInt Int64
-$8000000000000000 -9223372036854775808
$7FFFFFFFFFFFFFFF 9223372036854775807
NativeUInt UInt64
0 0
$FFFFFFFFFFFFFFFF 18446744073709551615
32-bit platforms include 32-bit Windows, OSX32, 32-bit iOS, and Android.
LongInt Integer
-$80000000 -2147483648
$7FFFFFFF 2147483647
LongWord Cardinal
0 0
$FFFFFFFF 4294967295
LongInt Int64
-$8000000000000000 -9223372036854775808
$7FFFFFFFFFFFFFFF 9223372036854775807
LongWord UInt64
0 0
$FFFFFFFFFFFFFFFF 18446744073709551615
const
Min = 0;
Max = 100;
Center = (Max - Min) div 2;
Beta = Chr(225);
NumChars = Ord('Z') - Ord('A') + 1;
Message = 'Out of memory';
ErrStr = ' Error: ' + Message + '. ';
ErrPos = 80 - Length(ErrStr) div 2;
Ln10 = 2.302585092994045684;
Ln10R = 1 / Ln10;
Numeric = ['0'..'9'];
Alpha = ['A'..'Z', 'a'..'z'];
AlphaNum = Alpha + Numeric;
Constant Expressions
A constant expression is an expression that the compiler can evaluate without
executing the program in which it occurs. Constant expressions include
numerals; character strings; true constants; values of enumerated types; the
special constants True, False, and nil; and expressions built exclusively from these
elements with operators, typecasts, and set constructors. Constant expressions
cannot include variables, pointers, or function calls, except calls to the following
predefined functions:
Abs High Low Pred Succ
100
'A'
256 - 1
(2.5 + 1) / (2.5 - 1)
'Embarcadero' + ' ' + 'Developer'
Chr(32)
Ord('Z') - Ord('A') + 1
Resource strings are declared as other true constants, except that the word
const is replaced by resourcestring. The expression to the right of the = symbol
must be a constant expression and must return a string value. For example:
resourcestring
CreateError = 'Cannot create file %s';
OpenError = 'Cannot open file %s';
LineTooLong = 'Line too long';
ProductName = 'Embarcadero Rocks';
SomeResourceString = SomeTrueConstant;
Typed Constants
Typed constants, unlike true constants, can hold values of array, record,
procedural, and pointer types. Typed constants cannot occur in constant
expressions.
where identifier is any valid identifier, type is any type except files and variants,
and value is an expression of type. For example,
const Max: Integer = 100;
Array Constants
To declare an array constant, enclose the values of the elements of the array,
separated by commas, in parentheses at the end of the declaration. These
values must be represented by constant expressions. For example:
Maze[0,0,0] = 0
Maze[0,0,1] = 1
Maze[0,1,0] = 2
Maze[0,1,1] = 3
Maze[1,0,0] = 4
Maze[1,0,1] = 5
Maze[1,1,0] = 6
Maze[1,1,1] = 7
Record Constants
To declare a record constant, specify the value of each field - as fieldName:
value, with the field assignments separated by semicolons - in parentheses at the
end of the declaration. The values must be represented by constant expressions.
The fields must be listed in the order in which they appear in the record type
declaration, and the tag field, if there is one, must have a value specified; if the
record has a variant part, only the variant selected by the tag field can be
assigned values.
type
TPoint = record
X, Y: Single;
end;
TVector = array[0..1] of TPoint;
TMonth = (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec);
TDate = record
D: 1..31;
M: TMonth;
Y: 1900..1999;
end;
const
Origin: TPoint = (X: 0.0; Y: 0.0);
Line: TVector = ((X: -3.1; Y: 1.5), (X: 5.8; Y: 3.0));
SomeDay: TDate = (D: 2; M: Dec; Y: 1960);
Procedural Constants
To declare a procedural constant, specify the name of a function or procedure
that is compatible with the declared type of the constant. For example,
Given these declarations, you can use the procedural constant MyFunction in a
function call:
I := MyFunction(5, 7)
Pointer Constants
When you declare a pointer constant, you must initialize it to a value that can be
resolved at least as a relative address at compile time. There are three ways to
do this: with the @ operator, with nil, and (if the constant is of type PChar or
PWideChar) with a string literal. For example, if I is a global variable of type
Integer, you can declare a constant like:
The compiler can resolve this because global variables are part of the code
segment. So are functions and global constants:
Because string literals are allocated as global constants, you can initialize a
PChar constant with a string literal:
const WarningStr: PChar = 'Warning!';
With $J+ set, you can use assignment statements to change the value of typed
constants as if they were initialized variables. For example:
{$J+}
const
foo: Integer = 12;
begin
foo := 14;
end.
Topics
o Procedures and Functions (Delphi)
o Parameters (Delphi)
o Calling conventions
calls SomeFunction and assigns the result to I. Function calls cannot appear on
the left side of an assignment statement.
Procedure calls - and, when extended syntax is enabled ({$X+}), function calls -
can be used as complete statements. For example:
DoSomething;
Given this declaration, you can call the NumString procedure like this:
NumString(17, MyString);
This procedure call assigns the value '17' to MyString (which must be a string
variable).
Within a statement block of a procedure, you can use variables and other
identifiers declared in the localDeclarations part of the procedure. You can also
use the parameter names from the parameter list (like N and S in the previous
example); the parameter list defines a set of local variables, so do not try to
redeclare the parameter names in the localDeclarations section. Finally, you can
use any identifiers within whose scope the procedure declaration falls.
Function Declarations
A function declaration is like a procedure declaration except that it specifies a
return type and a return value. Function declarations have the form:
The statement block of the function is governed by the same rules that apply to
procedures. Within the statement block, you can use variables and other
identifiers declared in the localDeclarations part of the function, parameter
names from the parameter list, and any identifiers within whose scope the
function declaration falls. In addition, the function name itself acts as a special
variable that holds the return value of the function, as does the predefined
variable Result.
For example:
You can assign a value to Result or to the function name repeatedly within a
statement block, as long as you assign only values that match the declared
Result and the function name always represent the same value. Hence:
returns the value 11. But Result is not completely interchangeable with the
function name. When the function name appears on the left side of an
assignment statement, the compiler assumes that it is being used (like Result) to
track the return value; when the function name appears anywhere else in the
statement block, the compiler interprets it as a recursive call to the function itself.
Result, on the other hand, can be used as a variable in operations, typecasts, set
constructors, indexes, and calls to other routines.
If the function exits without assigning a value to Result or the function name, then
the function's return value is undefined.
Calling Conventions
When you declare a procedure or function, you can specify a calling
convention using one of the directives register, pascal, cdecl, stdcall, safecall,
and winapi. For example,
function MyFunction(X, Y: Real): Real; cdecl;
Calling conventions determine the order in which parameters are passed to the
routine. They also affect the removal of parameters from the stack, the use of
registers for passing parameters, and error and exception handling. The default
calling convention is register.
o The cdecl, stdcall, and safecall conventions pass parameters from right to
left.
Calling conventions :
The default register convention is the most efficient, since it usually avoids
creation of a stack frame. (Access methods for published properties must use
register.) The cdecl convention is useful when you call functions from shared
libraries written in C or C++, while stdcall and safecall are recommended, in
general, for calls to external code. On Win32, the operating system APIs are
stdcall and safecall. Other operating systems generally use cdecl. (Note that
stdcall is more efficient than cdecl.)
The safecall convention must be used for declaring dual-interface methods. The
pascal convention is maintained for backward compatibility.
Ordinarily, a defining declaration does not have to repeat the parameter list or
return type of the routine, but if it does repeat them, they must match those in
the forward declaration exactly (except that default parameters can be
omitted). If the forward declaration specifies an overloaded procedure or
function, then the defining declaration must repeat the parameter list.
A forward declaration and its defining declaration must appear in the same type
declaration section. That is, you cannot add a new section (such as a var
section or const section) between the forward declaration and the defining
declaration. The defining declaration can be an external or assembler
declaration, but it cannot be another forward declaration.
The forward directive has no effect in the interface section of a unit. Procedure
and function headers in the interface section behave like forward declarations
and must have defining declarations in the implementation section. A routine
declared in the interface section is available from anywhere else in the unit and
from any other unit or program that uses the unit where it is declared.
External Declarations
The external directive, which replaces the block in a procedure or function
declaration, allows you to call routines that are compiled separately from your
The varargs directive works only with external routines and only with the cdecl
calling convention.
{$L BLOCK.OBJ}
links BLOCK.OBJ into the program or unit in which it occurs. Next, declare the
functions and procedures that you want to call:
Now you can call the MoveWord and FillWord routines from BLOCK.OBJ.
On the Win32 platform, declarations like the ones above are frequently used to
access external routines written in assembly language. You can also place
assembly-language routines directly in your Delphi source code.
where stringConstant1 gives the name of the library file and stringConstant2 is
the original name of the routine.
In your importing declaration, be sure to match the exact spelling and case of
the name of the routine. Later, when you call the imported routine, the name is
case-insensitive.
delayed ensures that the library that contains the imported function is not loaded
at application startup, but rather when the first call to the function is made. For
more information on this topic, see the Libraries and Packages - Delayed
Loading topic.
These declarations create two functions, both called Divide, that take
parameters of different types. When you call Divide, the compiler determines
which function to invoke by looking at the actual parameters passed in the call.
For example, Divide(6.0, 3.0) calls the first Divide function, because its arguments
are real-valued.
You can pass to an overloaded routine parameters that are not identical in type
with those in any of the declarations of the routine, but that are assignment-
compatible with the parameters in more than one declaration. This happens
most frequently when a routine is overloaded with different integer types or
different real types - for example:
procedure Store(X: Longint); overload;
procedure Store(X: Shortint); overload;
are legal.
This can cause some minor side effects with float types. Float types are matched
by size. If there is no exact match for the float variable passed to the overload
call but a variant parameter is available, the variant is taken over any smaller
float type.
For example:
procedure foo(i: integer); overload;
procedure foo(d: double); overload;
procedure foo(v: variant); overload;
var
v: variant;
begin
foo(1); // integer version
foo(v); // variant version
foo(1.2); // variant version (float literals -> extended precision)
end;
This example calls the variant version of foo, not the double version, because the
1.2 constant is implicitly an extended type and extended is not an exact match
for double. Extended is also not an exact match for Variant, but Variant is
considered a more general type (whereas double is a smaller type than
extended).
foo(Double(1.2));
This typecast does not work. You should use typed consts instead:
const d: double = 1.2;
begin
foo(d);
end;
The above code works correctly, and calls the double version.
The above code also calls the double version of foo. Single is a better fit to
double than to variant.
When declaring a set of overloaded routines, the best way to avoid float
promotion to variant is to declare a version of your overloaded function for each
float type (Single, Double, Extended) along with the variant version.
Local Declarations
The body of a function or procedure often begins with declarations of local
variables used in the statement block of the routine. These declarations can also
include constants, types, and other routines. The scope of a local identifier is
limited to the routine where it is declared.
Nested Routines
Functions and procedures sometimes contain other functions and procedures
within the local-declarations section of their blocks. For example, the following
declaration of a procedure called DoSomething contains a nested procedure.
procedure DoSomething(S: string);
var
X, Y: Integer;
begin
...
NestedProc(S);
...
end;
o Parameter semantics
o String parameters
o Array parameters
o Default parameters
About Parameters
Most procedure and function headers include a parameter list. For example, in
the header:
function Power(X: Real; Y: Integer): Real;
The parameter list specifies the number, order, and type of parameters that must
be passed to the routine when it is called. If a routine does not take any
parameters, omit the identifier list and the parentheses in its declaration:
procedure UpdateRecords;
begin
...
end;
Within the procedure or function body, the parameter names (X and Y in the first
example) can be used as local variables. Do not redeclare the parameter
names in the local declarations section of the procedure or function body.
o Value parameters are always typed, while constant, variable, and out
parameters can be either typed or untyped.
Files and instances of structured types that contain files can be passed only as
variable (var) parameters.
These functions return the same result, but only the second one - DoubleByRef
can change the value of a variable passed to it. Suppose we call the functions
like this:
var
I, J, V, W: Integer;
begin
I := 4;
V := 4;
J := DoubleByValue(I); // J = 8, I = 4
W := DoubleByRef(V); // W = 8, V = 8
end;
After this code executes, the variable I, which was passed to DoubleByValue,
has the same value we initially assigned to it. But the variable V, which was
passed to DoubleByRef, has a different value.
A variable parameter, on the other hand, acts like a pointer rather than a copy.
Changes made to the parameter within the body of a function or procedure
persist after program execution returns to the caller and the parameter name
itself has gone out of scope.
Even if the same variable is passed in two or more var parameters, no copies are
made. This is illustrated in the following example:
var I: Integer;
begin
I := 1;
AddOne(I, I);
end;
Constant Parameters
A constant (const) parameter is like a local constant or read-only variable.
Constant parameters are similar to value parameters, except that you cannot
assign a value to a constant parameter within the body of a procedure or
function, nor can you pass one as a var parameter to another routine. (But when
you pass an object reference as a constant parameter, you can still modify the
object's properties.)
Using const allows the compiler to optimize code for structured - and string-type
parameters. It also provides a safeguard against unintentionally passing a
parameter by reference to another routine.
Because S1 and S2 are not modified in the body of CompareStr, they can be
declared as constant parameters.
The following example shows how you can specify the [Ref] decorator either
before or after the const keyword:
Out Parameters
An out parameter, like a variable parameter, is passed by reference. With an out
parameter, however, the initial value of the referenced variable is discarded by
the routine it is passed to. The out parameter is for output only; that is, it tells the
function or procedure where to store output, but does not provide any input.
When you call GetInfo, you must pass it a variable of type SomeRecordType:
var MyRecord: SomeRecordType;
...
GetInfo(MyRecord);
But you're not using MyRecord to pass any data to the GetInfo procedure;
MyRecord is just a container where you want GetInfo to store the information it
generates. The call to GetInfo immediately frees the memory used by MyRecord,
before program control passes to the procedure.
Out parameters are frequently used with distributed-object models like COM. In
addition, you should use out parameters when you pass an uninitialized variable
to a function or procedure.
The following example uses untyped parameters in a function called Equal that
compares a specified number of bytes of any two variables:
String Parameters
When you declare routines that take short-string parameters, you cannot include
length specifiers in the parameter declarations. That is, the following declaration
causes a compilation error:
The special identifier OpenString can be used to declare routines that take short-
string parameters of varying length:
When the {$H} and {$P+} compiler directives are both in effect, the reserved
word string is equivalent to OpenString in parameter declarations.
Short strings, OpenString, $H, and $P are supported for backward compatibility
only. In new code, you can avoid these considerations by using long strings.
Array Parameters
When you declare routines that take array parameters, you cannot include
index type specifiers in the parameter declarations. That is, the declaration:
Since the Delphi language does not implement value semantics for dynamic
arrays, 'value' parameters in routines do not represent a full copy of the dynamic
array. In this example:
type
TDynamicArray = array of Integer;
procedure p(Value: TDynamicArray);
begin
Value[0] := 1;
end;
procedure Run;
var
a: TDynamicArray;
begin
SetLength(a, 1);
a[0] := 0;
p(a);
Writeln(a[0]); // Prints '1'
end;
Note that the assignment to Value[0] in routine p will modify the content of
dynamic array of the caller, despite Value being a by-value parameter. If a full
copy of the dynamic array is required, use the Copy standard procedure to
create a value copy of the dynamic array.
declares a function called Find that takes a character array of any size and
returns an integer.
Within the body of a routine, open array parameters are governed by the
following rules:
o They are always zero-based. The first element is 0, the second element is 1,
and so forth. The standard Low and High functions return 0 and Length - 1,
respectively. The SizeOf function returns the size of the actual array passed
to the routine.
o They can be passed to other procedures and functions only as open array
parameters or untyped var parameters. They cannot be passed to
SetLength.
When you pass an array as an open array value parameter, the compiler
creates a local copy of the array within the routine's stack frame. Be careful not
to overflow the stack by passing large arrays.
The following examples use open array parameters to define a Clear procedure
that assigns zero to each element in an array of reals and a Sum function that
computes the sum of the elements in an array of reals:
When you call routines that use open array parameters, you can pass open
array constructors to them.
The following Win32 example, uses a variant open array parameter in a function
that creates a string representation of each element passed to it and
concatenates the results into a single string. The string-handling routines called in
this function are defined in SysUtils:
We can call this function using an open array constructor. For example:
Default Parameters
You can specify default parameter values in a procedure or function heading.
Default values are allowed only for typed const and value parameters. To
provide a default value, end the parameter declaration with the = symbol
followed by a constant expression that is assignment-compatible with the
parameter's type.
Parameters with default values must occur at the end of the parameter list. That
is, all parameters following the first declared default value must also have default
values. So the following declaration is illegal:
procedure MyProcedure(I: Integer = 1; S: string); // syntax error
the statements:
F := Resizer;
F(N);
o only assignable expressions can be used to pass var and out parameters.
When you call a routine that uses default parameter values, all actual
parameters following the first accepted default must also use the default values;
calls of the form SomeFunction(,,X) are not legal.
You can omit parentheses when passing all and only the default parameters to a
routine. For example, given the procedure:
DoSomething();
DoSomething;
Open array constructors can be passed only as value or const parameters. The
expressions in a constructor must be assignment-compatible with the base type
of the array parameter. In the case of a variant open array parameter, the
expressions can be of different types.
o Inlining will not occur on any form of late-bound method. This includes
virtual, dynamic, and message methods.
o The main program block, unit initialization, and unit finalization blocks
cannot be inlined.
o If a routine marked with inline uses external symbols from other units, all of
those units must be listed in the uses statement, otherwise the routine
cannot be inlined.
o Within a unit, the body for an inline function should be defined before
calls to the function are made. Otherwise, the body of the function, which
is not known to the compiler when it reaches the call site, cannot be
expanded inline.
If you modify the implementation of an inlined routine, you will cause all units
that use that function to be recompiled. This is different from traditional rebuild
rules, where rebuilds were triggered only by changes in the interface section of a
unit.
The {$INLINE} compiler directive gives you finer control over inlining. The {$INLINE}
directive can be used at the site of the inlined definition of the routine, as well as
at the call site. Below are the possible values and their meaning:
{$INLINE Behaves like {$INLINE ON}, with the {$INLINE AUTO} has no effect on
AUTO} addition that routines not marked with whether a routine will be inlined
inline will be inlined if their code size is when it is used at the call site of
less than or equal to 32 bytes. the routine.
{$INLINE The routine will not be marked as The routine will not be expanded
OFF} inlineable, even if it is tagged with inline. inline.
Note: This topic covers handling Delphi anonymous method in Delphi code. For
C++ code, see How to Handle Delphi Anonymous Methods in C++.
Syntax
An anonymous method is defined similarly to a regular procedure or function,
but with no name.
type
TFuncOfInt = reference to function(x: Integer): Integer;
o is a function
type
TType1 = reference to procedure (parameterlist);
TType2 = reference to function (parameterlist): returntype;
// Procedure
procedure (parameters)
begin
{ statement block }
end;
// Function
function (parameters): returntype
begin
{ statement block }
end;
var
m: TMethRef;
i: TMyClass;
begin
// ...
m := i.Method; //assigning to method reference
end;
However, the converse is not true: you cannot assign an anonymous method to
a regular method pointer. Method references are managed types, but method
pointers are unmanaged types. Thus, for type-safety reasons, assigning method
references to method pointers is not supported. For instance, events are method
pointer-valued properties, so you cannot use an anonymous method for an
event. See the section on variable binding for more information on this restriction.
var
adder: TFuncOfInt;
begin
adder := MakeAdder(20);
Writeln(adder(22)); // prints 42
end.
The variable adder contains an anonymous method that binds the value 20 to
the variable y referenced in the anonymous method's code block. This binding
persists even if the value goes out of scope.
type
TProc = reference to procedure;
TMyComponent = class(TComponent)
private
FMyEvent: TProc;
public
// MyEvent property serves as an event:
property MyEvent: TProc read FMyEvent write FMyEvent;
// some other code invokes FMyEvent as usual pattern for events
end;
// …
var
c: TMyComponent;
begin
c := TMyComponent.Create(Self);
c.MyEvent := procedure
begin
ShowMessage('Hello World!'); // shown when TMyComponent invokes MyEvent
end;
end;
Anonymous method values are of the method reference type, and are
reference-counted. When the last method reference to a given anonymous
method value goes out of scope, or is cleared (initialized to nil) or finalized, the
variables it has captured finally go out of scope.
type
TProc = reference to procedure;
procedure Call(proc: TProc);
// ...
procedure Use(x: Integer);
// ...
begin
Call(procedure // frame F1_2
var
v2: Integer;
begin
Use(v1);
Call(procedure // frame F1_2_1
begin
Use(v2);
end);
end);
end;
o v1 is a variable in F1
Frames F1_2_1 and F1_1_1 do not need frame objects, since they neither declare
anonymous methods nor have variables that are captured. They are not on any
path of parentage between a nested anonymous method and an outer
captured variable either. (They have implicit frames stored on the stack.)
Variable Binding
Anonymous methods provide a block of code along with variable bindings to
the environment in which they are defined, even if that environment is not in
scope. A pointer to a function or procedure cannot do that.
For instance, the statement adder := MakeAdder(20); from the code sample
above produces a variable adder that encapsulates the binding of a variable to
the value 20.
type
TMethodPointer = procedure of object; // delegate void TMethodPointer();
TStringToInt = function(x: string): Integer of object;
TObj = class
procedure HelloWorld;
function GetLength(x: string): Integer;
end;
procedure TObj.HelloWorld;
begin
Writeln('Hello World');
end;
var
x: TMethodPointer;
y: TStringToInt;
obj: TObj;
begin
obj := TObj.Create;
x := obj.HelloWorld;
x;
y := obj.GetLength;
Writeln(y('foo'));
end.
type
TSimpleProcedure = reference to procedure;
TSimpleFunction = reference to function(x: string): Integer;
var
x1: TSimpleProcedure;
y1: TSimpleFunction;
begin
x1 := procedure
begin
Writeln('Hello World');
end;
x1; //invoke anonymous method just defined
Notice how much simpler and shorter the code is that uses anonymous methods.
This is ideal if you want to explicitly and simply define these methods and use
them immediately without the overhead and effort of creating a class that may
never be used anywhere else. The resulting code is easier to understand.
type
TProcOfInteger = reference to procedure(x: Integer);
procedure CalculateExpensiveThings;
var
results: array of Integer;
begin
SetLength(results, 100);
ParallelFor(Low(results), High(results),
procedure(i: Integer) // \
begin // \ code block
results[i] := ExpensiveCalculation(i); // / used as parameter
end // /
);
// use results
end;
Topics
o Classes and Objects (Delphi)
o Fields (Delphi)
o Methods (Delphi)
o Properties (Delphi)
o Events (Delphi)
o Class References
o Exceptions (Delphi)
Class Types
A class, or class type, defines a structure consisting of fields, methods, and
properties. Instances of a class type are called objects. The fields, methods, and
properties of a class are called its components or members.
A class type must be declared and given a name before it can be instantiated.
(You cannot define a class type within a variable declaration.) Declare classes
only in the outermost scope of a program or unit, not in a procedure or function
declaration.
A class cannot be both abstract and sealed. The [abstract | sealed] syntax
(the [ ] brackets and the | pipe between them) is used to specify that only one
of the optional sealed or abstract keywords can be used. Only the sealed or
abstract keywords are meaningful. The brackets and pipe symbols should be
deleted.
For example, here is the declaration of the TMemoryStream class from the Classes
unit:
var
stream: TMemoryStream;
begin
stream := TMemoryStream.Create;
The scope of a member's identifier starts at the point where the member is
declared, continues to the end of the class declaration, and extends over all
If the declaration of a class type does not specify an ancestor, the class inherits
directly from System.TObject. Thus:
is equivalent to:
the variable Fig can be assigned values of type TFigure, TRectangle, and
TSquare.
Object Types
The Delphi compiler allows an alternative syntax to class types. You can declare
object types using the syntax:
Since object types do not descend from System.TObject, they provide no built-in
constructors, destructors, or other methods. You can create instances of an
object type using the New procedure and destroy them with the Dispose
procedure, or you can simply declare variables of an object type, just as you
would with records.
Object types are supported for backward compatibility only. Their use is not
recommended.
declares a published property called Color. Visibility determines where and how
a member can be accessed, with private representing the least accessibility,
protected representing an intermediate level of accessibility, and public,
published, and automated representing the greatest accessibility.
If a member's declaration appears without its own visibility specifier, the member
has the same visibility as the one that precedes it. Members at the beginning of
a class declaration that do not have a specified visibility are by default
published, provided the class is compiled in the {$M+} state or is derived from a
class compiled in the {$M+} state; otherwise, such members are public.
For readability, it is best to organize a class declaration by visibility, placing all the
private members together, followed by all the protected members, and so forth.
This way each visibility reserved word appears at most once and marks the
beginning of a new 'section' of the declaration. So a typical class declaration
should be like this:
A protected member is visible anywhere in the module where its class is declared
and from any descendent class, regardless of the module where the
descendent class appears. A protected method can be called, and a protected
field or property read or written to, from the definition of any method belonging
to a class that descends from the one where the protected member is declared.
Members that are intended for use only in the implementation of derived classes
are usually protected.
Class members with strict private visibility are accessible only within the class in
which they are declared. They are not visible to procedures or functions
declared within the same unit. Class members with strict protected visibility are
visible within the class in which they are declared, and within any descendent
class, regardless of where it is declared. Furthermore, when instance members
Published Members
Published members have the same visibility as public members. The difference is
that run-time type information (RTTI) is generated for published members. RTTI
allows an application to query the fields and properties of an object dynamically
and to locate its methods. RTTI is used to access the values of properties when
saving and loading form files, to display properties in the Object Inspector, and
to associate specific methods (called event handlers) with specific properties
(called events).
Published properties are restricted to certain data types. Ordinal, string, class,
interface, variant, and method-pointer types can be published. So can set types,
provided the upper and lower bounds of the base type have ordinal values from
0 through 31. (In other words, the set must fit in a byte, word, or double word.)
Any real type except Real48 can be published. Properties of an array type (as
distinct from array properties, discussed below) cannot be published.
Some properties, although publishable, are not fully supported by the streaming
system. These include properties of record types, array properties of all
publishable types, and properties of enumerated types that include anonymous
values. If you publish a property of this kind, the Object Inspector will not display it
correctly, nor will the property's value be preserved when objects are streamed
to disk.
All methods are publishable, but a class cannot publish two or more overloaded
methods with the same name. Fields can be published only if they are of a class
or interface type.
A class cannot have published members unless it is compiled in the {$M+} state
or descends from a class compiled in the {$M+} state. Most classes with
published members derive from Classes.TPersistent, which is compiled in the
{$M+} state, so it is seldom necessary to use the $M directive.
o Property declarations can include access specifiers (read and write) but
other specifiers (index, stored, default, and nodefault) are not allowed.
Access specifiers must list a method identifier that uses the default register
calling convention; field identifiers are not allowed.
with no ancestor or class members listed after the word class, then it is a forward
declaration. A forward declaration must be resolved by a defining declaration
of the same class within the same type declaration section. In other words,
type
TFigure = class; // forward declaration
TDrawing = class
Figure: TFigure;
// ...
end;
Fields (Delphi)
This topic describes the syntax of class data fields declarations.
About Fields
A field is like a variable that belongs to an object. Fields can be of any type,
including class types. (That is, fields can hold object references.) Fields are usually
private.
To define a field member of a class, simply declare the field as you would a
variable. For example, the following declaration creates a class called TNumber
whose only member, other than the methods inherited from System.TObject, is
an integer field called Int:
type
TNumber = class
var
Int: Integer;
end;
The var keyword is optional. However, if it is not used, then all field declarations
must occur before any property or method declarations. After any property or
method declarations, the var may be used to introduce any additional field
declarations.
type
TAncestor = class
Value: Integer;
end;
TDescendant = class(TAncestor)
Value: string; // hides the inherited Value field
end;
var
MyObject: TAncestor;
begin
MyObject := TDescendant.Create;
MyObject.Value := 'Hello!' // error
Declarations of constants and typed constants can appear in classes and non-
anonymous records at global scope. Both constants and typed constants can
also appear within nested type definitions. Constants and typed constants can
appear only within class definitions when the class is defined locally to a
procedure (i.e. they cannot appear within records defined within a procedure).
Class Fields
Class fields are data fields in a class that can be accessed without an object
reference (unlike the normal "instance fields" which are discussed above). The
data stored in a class field are shared by all instances of the class and may be
accessed by referring to the class or to a variable that represents an instance of
the class.
You can introduce a block of class fields within a class declaration by using the
class var block declaration. All fields declared after class var have static storage
attributes. A class var block is terminated by the following:
For example:
type
TMyClass = class
public
class var // Introduce a block of class static fields.
Red: Integer;
Green: Integer;
Blue: Integer;
var // Ends the class var block.
InstanceField: Integer;
end;
The class fields Red, Green, and Blue can be accessed with the code:
TMyClass.Red := 1;
TMyClass.Green := 2;
TMyClass.Blue := 3;
Class fields may also be accessed through an instance of the class. With the
following declaration:
var
myObject: TMyClass;
This code has the same effect as the assignments to Red, Green, and Blue
above:
myObject.Red := 1;
myObject.Green := 2;
myObject.Blue := 3;
Methods (Delphi)
A method is a procedure or function associated with a class. A call to a method
specifies the object (or, if it is a class method, the class) that the method should
operate on. For example, SomeObject.Free calls the Free method in
SomeObject.
o Method binding
o Overloading methods
o Message methods
About Methods
Within a class declaration, methods appear as procedure and function
headings, which work like forward declarations. Somewhere after the class
declaration, but within the same module, each method must be implemented
by a defining declaration. For example, suppose the declaration of TMyClass
includes a method called DoSomething:
type
TMyClass = class(TObject)
...
procedure DoSomething;
...
end;
Method declarations can include special directives that are not used with other
functions or procedures. Directives should appear in the class declaration only,
not in the defining declaration, and should always be listed in the following
order:
Where:
Inherited
The reserved word inherited plays a special role in implementing polymorphic
behavior. It can occur in method definitions, with or without an identifier after it.
inherited Create(...);
When inherited has no identifier after it, it refers to the inherited method with the
same name as the enclosing method or, if the enclosing method is a message
handler, to the inherited message handler for the same message. In this case,
inherited takes no explicit parameters, but passes to the inherited method the
same parameters with which the enclosing method was called. For example:
inherited;
Self
Within the implementation of a method, the identifier Self references the object
in which the method is called. For example, here is the implementation of
TCollection Add method in the Classes unit:
The Add method calls the Create method in the class referenced by the
FItemClass field, which is always a TCollectionItem descendant.
TCollectionItem.Create takes a single parameter of type TCollection, so Add
passes it the TCollection instance object where Add is called. This is illustrated in
the following code:
var MyCollection: TCollection;
...
MyCollection.Add // MyCollection is passed to the
// TCollectionItem.Create method
For information about Self in class methods, see "Class Operators" in Class
References.
Method Binding
Method bindings can be static (the default), virtual, or dynamic. Virtual and
dynamic methods can be overridden, and they can be abstract. These
designations come into play when a variable of one class type holds a value of
a descendent class type. They determine which implementation is activated
when a method is called.
Static Methods
Methods are by default static. When a static method is called, the declared
(compile-time) type of the class or object variable used in the method call
determines which implementation to activate. In the following example, the
Draw methods are static:
type
TFigure = class
procedure Draw;
end;
TRectangle = class(TFigure)
procedure Draw;
end;
Given these declarations, the following code illustrates the effect of calling a
static method. In the second call to Figure.Draw, the Figure variable references
an object of class TRectangle, but the call invokes the implementation of Draw in
TFigure, because the declared type of the Figure variable is TFigure:
begin
Figure := TFigure.Create;
Figure.Draw; // calls TFigure.Draw
Figure.Destroy;
Figure := TRectangle.Create;
Figure.Draw; // calls TFigure.Draw
Figure.Destroy;
Rectangle := TRectangle.Create;
Rectangle.Draw; // calls TRectangle.Draw
Rectangle.Destroy;
end;
TRectangle = class(TFigure)
procedure Draw; override;
end;
TEllipse = class(TFigure)
procedure Draw; override;
end;
var
Figure: TFigure;
begin
Figure := TRectangle.Create;
Figure.Draw; // calls TRectangle.Draw
Figure.Destroy;
Figure := TEllipse.Create;
Figure.Draw; // calls TEllipse.Draw
Figure.Destroy;
end;
Only virtual and dynamic methods can be overridden. All methods, however,
can be overloaded; see Overloading methods.
Final Methods
The Delphi compiler also supports the concept of final virtual and dynamic
methods. Declarations of final methods have the form:
Here the virtual|dynamic syntax (two keywords and the | pipe between them)
is used to specify that one and only one of the virtual or dynamic keywords
should be used. Meaningful is only the virtual or dynamic keyword; the pipe
symbol itself should be deleted.
Example
type
Base = class
procedure TestProcedure; virtual;
procedure TestFinalProcedure; virtual; final;
end;
Derived = class(Base)
procedure TestProcedure; override;
//Ill-formed: E2352 Cannot override a final method
procedure TestFinalProcedure; override;
end;
In general, virtual methods are the most efficient way to implement polymorphic
behavior. Dynamic methods are useful when a base class declares many
overridable methods that are inherited by many descendent classes in an
application, but only occasionally overridden.
T2 = class(T1)
procedure Act; // Act is redeclared, but not overridden
end;
var
SomeObject: T1;
begin
SomeObject := T2.Create;
SomeObject.Act; // calls T1.Act
end;
Reintroduce
The reintroduce directive suppresses compiler warnings about hiding previously
declared virtual methods. For example:
Use reintroduce when you want to hide an inherited virtual method with a new
one.
You can call an abstract method only in a class or instance of a class in which
the method has been overridden.
Class Methods
Most methods are called instance methods, because they operate on an
individual instance of an object. A class method is a method (other than a
constructor) that operates on classes instead of objects. There are two types of
class methods: ordinary class methods and class static methods.
The defining declaration of a class method must also begin with class. For
example:
class procedure TFigure.GetInfo(var Info: TFigureInfo);
begin
...
end;
In the defining declaration of a class method, the identifier Self represents the
class where the method is called (which can be a descendant of the class in
which it is defined.) If the method is called in the class C, then Self is of the type
class of C. Thus you cannot use Self to access instance fields, instance properties,
and normal (object) methods. You can use Self to call constructors and other
class methods, or to access class properties and class fields.
Methods are made class static by appending the word static to their
declaration, for example:
type
TMyClass = class
strict private
class var
FX: Integer;
strict protected
// Note: Accessors for class properties
// must be declared class static.
class function GetX: Integer; static;
class procedure SetX(val: Integer); static;
public
class property X: Integer read GetX write SetX;
class procedure StatProc(s: String); static;
end;
Like a class method, you can call a class static method through the class type
(for example, without having an object reference), such as:
TMyClass.X := 17;
TMyClass.StatProc('Hello');
Overloading Methods
A method can be redeclared using the overload directive. In this case, if the
redeclared method has a different parameter signature from its ancestor, it
overloads the inherited method without hiding it. Calling the method in a
descendent class activates whichever implementation matches the parameters
in the call.
type
T1 = class(TObject)
procedure Test(I: Integer); overload; virtual;
end;
T2 = class(T1)
procedure Test(S: string); reintroduce; overload;
end;
...
SomeObject := T2.Create;
SomeObject.Test('Hello!'); // calls T2.Test
SomeObject.Test(7); // calls T1.Test
Within a class, you cannot publish multiple overloaded methods with the same
name. Maintenance of run time type information requires a unique name for
each published member:
type
TSomeClass = class
published
function Func(P: Integer): Integer;
function Func(P: Boolean): Integer; // error
...
Constructors
A constructor is a special method that creates and initializes instance objects.
The declaration of a constructor looks like a procedure declaration, but it begins
with the word constructor. Examples:
constructor Create;
constructor Create(AOwner: TComponent);
Constructors must use the default register calling convention. Although the
declaration specifies no return value, a constructor returns a reference to the
object it creates or is called in.
A class can have more than one constructor, but most have only one. It is
conventional to call the constructor Create.
MyObject := TMyClass.Create;
This allocates storage for the new object, sets the values of all ordinal fields to
zero, assigns nil to all pointer and class-type fields, and makes all string fields
empty. Other actions specified in the constructor implementation are performed
next; typically, objects are initialized based on values passed as parameters to
the constructor. Finally, the constructor returns a reference to the newly
allocated and initialized object. The type of the returned value is the same as the
class type specified in the constructor call.
Destructors
A destructor is a special method that destroys the object where it is called and
deallocates its memory. The declaration of a destructor looks like a procedure
declaration, but it begins with the word destructor. Example:
Destructors on Win32 must use the default register calling convention. Although a
class can have more than one destructor, it is recommended that each class
override the inherited Destroy method and declare no other destructors.
MyObject.Destroy;
Class Constructors
A class constructor is a special class method that is not accessible to developers.
Calls to class constructors are inserted automatically by the compiler into the
initialization section of the unit where the class is defined. Normally, class
constructors are used to initialize the static fields of the class or to perform a type
of initialization, which is required before the class or any class instance can
function properly. Even though the same result can be obtained by placing class
initialization code into the initialization section, class constructors have the
benefit of helping the compiler decide which classes should be included into the
final binary file and which should be removed from it.
The next example shows the usual way of initializing class fields:
type
TBox = class
private
class var FList: TList<Integer>;
end;
implementation
initialization
{ Initialize the static FList member }
TBox.FList := TList<Integer>.Create();
end.
type
TBox = class
private
class var FList: TList<Integer>;
class constructor Create;
end;
implementation
end.
In this case, the compiler checks whether TBox is actually used anywhere in the
application, and if it is used, a call to the class constructor is added
automatically to the initialization section of the unit.
Note: Even though the compiler takes care of ordering the initialization of classes,
in some complex scenarios, ordering may become random. This happens when
the class constructor of a class depends on the state of another class that, in
turn, depends on the first class.
Note: The class constructor for a generic class or record may execute multiple
times. The exact number of times the class constructor is executed in this case
depends on the number of specialized versions of the generic type. For example,
the class constructor for a specialized TList<String> class may execute multiple
times in the same application.
Class Destructors
Class destructors are the opposite of class constructors in that they perform the
finalization of the class. Class destructors come with the same advantages as
class constructors, except for finalization purposes.
type
TBox = class
private
class var FList: TList<Integer>;
class constructor Create;
class destructor Destroy;
end;
implementation
end.
Note: The class destructor for a generic class or record may execute multiple
times. The exact number of times the class destructor is executed in this case
depends on the number of specialized versions of the generic type. For example,
the class destructor for a specialized TList<String> class may execute multiple
times in the same application.
Message Methods
Message methods implement responses to dynamically dispatched messages.
The message method syntax is supported on all platforms. VCL uses message
methods to respond to Windows messages.
For example:
type
TTextBox = class(TCustomControl)
private
procedure WMChar(var Message: TWMChar); message WM_CHAR;
...
end;
The inherited statement searches backward through the class hierarchy and
invokes the first message method with the same ID as the current method,
automatically passing the message record to it. If no ancestor class implements
a message method for the given ID, inherited calls the DefaultHandler method
originally defined in TObject.
Message Dispatching
Message handlers are seldom called directly. Instead, messages are dispatched
to an object using the Dispatch method inherited from TObject:
The Message parameter passed to Dispatch must be a record whose first entry is
a field of type Word containing a message ID.
Dispatch searches backward through the class hierarchy (starting from the class
of the object where it is called) and invokes the first message method for the ID
passed to it. If no message method is found for the given ID, Dispatch calls
DefaultHandler.
o Property access
o Array properties
o Index specifiers
o Storage specifiers
o Class properties
About Properties
A property, like a field, defines an attribute of an object. But while a field is
merely a storage location whose contents can be examined and changed, a
property associates specific actions with reading or modifying its data. Properties
provide control over access to an object's attributes, and they allow attributes to
be computed.
The declaration of a property specifies a name and a type, and includes at least
one access specifier. The syntax of a property declaration is:
where
Properties are defined by their access specifiers. Unlike fields, properties cannot
be passed as var parameters, nor can the @ operator be applied to a property.
The reason is that a property doesn't necessarily exist in memory. It could, for
Property Access
Every property has a read specifier, a write specifier, or both. These are called
access specifiers and they have the form:
read fieldOrMethod
write fieldOrMethod
When a property is referenced in an expression, its value is read using the field or
method listed in the read specifier. When a property is referenced in an
assignment statement, its value is written using the field or method listed in the
write specifier.
The example below declares a class called TCompass with a published property
called Heading. The value of Heading is read through the FHeading field and
written through the SetHeading procedure:
type
THeading = 0..359;
TCompass = class(TControl)
private
FHeading: THeading;
procedure SetHeading(Value: THeading);
published
property Heading: THeading read FHeading write SetHeading;
...
end;
correspond to:
if Compass.FHeading = 180 then GoingSouth;
Compass.SetHeading(135);
Array Properties
Array properties are indexed properties. They can represent things like items in a
list, child controls of a control, and pixels of a bitmap.
The declaration of an array property includes a parameter list that specifies the
names and types of the indexes. For example:
For array properties, access specifiers must list methods rather than fields. The
method in a read specifier must be a function that takes the number and type of
parameters listed in the property's index parameter list, in the same order, and
whose result type is identical to the property's type. The method in a write
specifier must be a procedure that takes the number and type of parameters
listed in the property's index parameter list, in the same order, plus an additional
value or const parameter of the same type as the property.
For example, the access methods for the array properties above might be
declared as:
correspond to:
If a class has a default property, you can access that property with the
abbreviation object[index], which is equivalent to object.property[index]. For
example, given the declaration above, StringArray.Strings[7] can be
abbreviated to StringArray[7]. A class can have only one default property with a
given signature (array parameter list), but it is possible to overload the default
property. Changing or hiding the default property in descendent classes may
lead to unexpected behavior, since the compiler always binds to properties
statically.
type
TRectangle = class
private
FCoordinates: array[0..3] of Longint;
function GetCoordinate(Index: Integer): Longint;
procedure SetCoordinate(Index: Integer; Value: Longint);
public
property Left: Longint index 0 read GetCoordinate
write SetCoordinate;
property Top: Longint index 1 read GetCoordinate
write SetCoordinate;
property Right: Longint index 2 read GetCoordinate
write SetCoordinate;
property Bottom: Longint index 3 read GetCoordinate
write SetCoordinate;
property Coordinates[Index: Integer]: Longint
read GetCoordinate
write SetCoordinate;
...
end;
An access method for a property with an index specifier must take an extra
value parameter of type Integer. For a read function, it must be the last
parameter; for a write procedure, it must be the second-to-last parameter
(preceding the parameter that specifies the property value). When a program
accesses the property, the property's integer constant is automatically passed to
the access method.
corresponds to:
Storage Specifiers
The optional stored, default, and nodefault directives are called storage
specifiers. They have no effect on program behavior, but control whether or not
to save the values of published properties in form files.
The default directive must be followed by a constant of the same type as the
property. For example:
To override an inherited default value without specifying a new one, use the
nodefault directive. The default and nodefault directives are supported only for
ordinal types and for set types, provided the upper and lower bounds of the set's
base type have ordinal values between 0 and 31; if such a property is declared
without default or nodefault, it is treated as if nodefault were specified. For reals,
pointers, and strings, there is an implicit default value of 0, nil, and '' (the empty
string), respectively.
Note: You can't use the ordinal value -2147483648 has a default
value. This value is used internally to represent nodefault.
Storage specifiers are not supported for array properties. The default directive
has a different meaning when used in an array property declaration. See Array
Properties, above.
type
TAncestor = class
...
protected
property Size: Integer read FSize;
property Text: string read GetText write SetText;
property Color: TColor read FColor write SetColor stored False;
...
end;
type
TDerived = class(TAncestor)
...
protected
property Size write SetSize;
published
property Text;
property Color stored True default clBlue;
...
end;
The override of Size adds a write specifier to allow the property to be modified.
The overrides of Text and Color change the visibility of the properties from
protected to published. The property override of Color also specifies that the
property should be filed if its value is not clBlue.
TDescendant = class(TAncestor)
...
property Value: Integer read Method3 write Method4;
end;
Class Properties
Class properties can be accessed without an object reference. Class property
accessors must themselves be declared as class static methods, or class fields. A
class property is declared with the class property keywords. Class properties
cannot be published, and cannot have stored or default value definitions.
You can introduce a block of class static fields within a class declaration by using
the class var block declaration. All fields declared after class var have static
storage attributes. A class var block is terminated by the following:
For example:
type
TMyClass = class
strict private
class var // Note fields must be declared as class fields
FRed: Integer;
FGreen: Integer;
FBlue: Integer;
public // ends the class var block
class property Red: Integer read FRed write FRed;
class property Green: Integer read FGreen write FGreen;
class property Blue: Integer read FBlue write FBlue;
end;
TMyClass.Red := 0;
TMyClass.Blue := 0;
TMyClass.Green := 0;
Events (Delphi)
This topic describes the following material:
About Events
An event links an occurrence in the system with the code that responds to that
occurrence. The occurrence triggers the execution of a procedure called an
event handler. The event handler performs the tasks that are required in
response to the occurrence. Events allow the behavior of a component to be
customized at design-time or at run time. To change the behavior of the
component, replace the event handler with a custom event handler that will
have the desired behavior.
{$APPTYPE CONSOLE}
type
{ Define a procedural type }
TPingEvent = procedure of object;
public
property OnPing: TPingEvent read FPing write FPing;
{ The listener }
TListener = class
procedure Ping;
end;
procedure TObservedObject.TriggerEvent;
begin
{ Call the registerd event only if there is a listener }
if Assigned(FPing) then
FPing();
end;
procedure TListener.Ping;
begin
Writeln('TListener has been pinged.');
end;
var
ObservedObject: TObservedObject;
Listener: TListener;
begin
{ Create object instances }
ObservedObject := TObservedObject.Create();
Listener := TListener.Create();
program EventDemo2;
{$APPTYPE CONSOLE}
type
{ Define a procedural type }
TPingEvent = procedure of object;
public
property OnPing: TPingEvent read FPing write FPing;
{ The listener }
TListener = class
procedure Ping;
end;
procedure TObservedObject.TriggerEvent;
begin
{ Call the registerd event only if there is a listener }
if Assigned(FPing) then
FPing();
end;
procedure TListener.Ping;
begin
Writeln('TListener has been pinged.');
end;
procedure TListenerSubclass.Ping2;
begin
{ Call the base class ping }
Self.Ping();
Writeln('TListenerSubclass has been pinged.');
end;
var
ObservedObject: TObservedObject;
begin
{ Create object instances }
ObservedObject := TObservedObject.Create();
Listener := TListenerSubclass.Create();
Class References
Sometimes operations are performed on a class itself, rather than on instances of
a class (that is, objects). This happens, for example, when you call a constructor
method using a class reference. You can always refer to a specific class using its
name, but sometimes it is necessary to declare variables or parameters that take
classes as values, and in these situations you need class-reference types.
o Class operators
Class-Reference Types
A class-reference type, sometimes called a metaclass, is denoted by a
construction of the form:
class of type
where type is any class type. The identifier type itself denotes a value whose type
is class of type. If type1 is an ancestor of type2, then class of type2 is assignment-
compatible with class of type1. Thus:
declares a variable called AnyObj that can hold a reference to any class. (The
definition of a class-reference type cannot occur directly in a variable
declaration or parameter list.) You can assign the value nil to a variable of any
class-reference type.
This declaration says that to create a TCollection instance object, you must pass
to the constructor the name of a class descending from TCollectionItem.
Class-reference types are useful when you want to invoke a class method or
virtual constructor on a class or object whose actual type is unknown at compile
time.
Constructors called using class references are usually virtual. The constructor
implementation activated by the call depends on the runtime type of the class
reference.
The is Operator
The is operator, which performs dynamic type checking, is used to verify the
actual runtime class of an object. The expression:
object is class
returns True if object is an instance of the class denoted by class or one of its
descendants, and False otherwise. (If object is nil, the result is False.) If the
declared type of object is unrelated to class -- that is, if the types are distinct and
one is not an ancestor of the other -- a compilation error results. For example:
if ActiveControl is TEdit then TEdit(ActiveControl).SelectAll;
This statement casts the ActiveControl variable to the TEdit type. First it verifies
that the object referenced by ActiveControl is an instance of TEdit or one of its
descendants.
The as Operator
The as operator performs checked typecasts. The expression
object as class
returns a reference to the same object as object, but with the type given by
class. At run time, object must be an instance of the class denoted by class or
one of its descendants, or be nil; otherwise an exception is raised. If the declared
type of object is unrelated to class - that is, if the types are distinct and one is not
an ancestor of the other - a compilation error results. For example:
Code Examples
o ClassParent (Delphi)
About Exceptions
An exception is raised when an error or other event interrupts normal execution
of a program. The exception transfers control to an exception handler, which
allows you to separate normal program logic from error-handling. Because
exceptions are objects, they can be grouped into hierarchies using inheritance,
and new exceptions can be introduced without affecting existing code. An
exception can carry information, such as an error message, from the point where
it is raised to the point where it is handled.
When an application uses the SysUtils unit, most runtime errors are automatically
converted into exceptions. Many errors that would otherwise terminate an
application - such as insufficient memory, division by zero, and general
protection faults - can be caught and handled.
Exception handling is appropriate for errors whose chances of occurring are low
or difficult to assess, but whose consequences are likely to be catastrophic (such
as crashing the application); for error conditions that are complicated or difficult
to test for in if...then statements; and when you need to respond to exceptions
raised by the operating system or by routines whose source code you don't
control. Exceptions are commonly used for hardware, memory, I/O, and
operating-system errors.
try
AssignFile(F, FileName);
Reset(F); // raises an EInOutError exception if file is not found
except
on Exception do ...
end;
But you could also avoid the overhead of exception handling by using:
begin
AssignFile(F, FileName);
Reset(F);
end;
You can group exceptions into families using inheritance. For example, the
following declarations in SysUtils define a family of exception types for math
errors:
type
EMathError = class(Exception);
EInvalidOp = class(EMathError);
EZeroDivide = class(EMathError);
EOverflow = class(EMathError);
EUnderflow = class(EMathError);
raise EMathError.Create;
where object and at address are both optional. When an address is specified, it
can be any expression that evaluates to a pointer type, but is usually a pointer to
a procedure or function. For example:
raise Exception.Create('Missing parameter') at @MyFunction;
Use this option to raise the exception from an earlier point in the stack than the
one where the error actually occurred.
Try...except Statements
Exceptions are handled within try...except statements. For example:
try
X := Y/Z;
except
on EZeroDivide do HandleZeroDivide;
end;
else statements
where identifier: is optional (if included, identifier can be any valid identifier),
type is a type used to represent exceptions, and statement is any statement.
If none of the conditions above is satisfied, the search continues in the exception
block of the next-most-recently entered try...except statement that has not yet
exited. If no appropriate handler, else clause, or statement list is found there, the
search propagates to the next-most-recently entered try...except statement,
and so forth. If the outermost try...except statement is reached and the
exception is still not handled, the program terminates.
If the exception block specifies an else clause, the else clause handles any
exceptions that aren't handled by the block's exception handlers. For example:
try
...
except
on EZeroDivide do HandleZeroDivide;
on EOverflow do HandleOverflow;
on EMathError do HandleMathError;
else
HandleAllOthers;
end;
Here, the else clause handles any exception that isn't an SysUtils.EMathError.
Here, the HandleException routine handles any exception that occurs as a result
of executing the statements between try and except.
Re-raising Exceptions
When the reserved word raise occurs in an exception block without an object
reference following it, it raises whatever exception is handled by the block. This
allows an exception handler to respond to an error in a limited way and then re-
raise the exception. Re-raising is useful when a procedure or function has to
clean up after an exception occurs but cannot fully handle the exception.
GetFileList creates a TStringList object, then uses the FindFirst and FindNext
functions (defined in SysUtils) to initialize it. If the initialization fails - for example
because the search path is invalid, or because there is not enough memory to fill
in the string list - GetFileList needs to dispose of the new string list, since the caller
does not yet know of its existence. For this reason, initialization of the string list is
performed in a try...except statement. If an exception occurs, the statement's
exception block disposes of the string list, then re-raises the exception.
Nested Exceptions
Code executed in an exception handler can itself raise and handle exceptions.
As long as these exceptions are also handled within the exception handler, they
do not affect the original exception. However, once an exception raised in an
exception handler propagates beyond that handler, the original exception is
lost. This is illustrated by the Tan function below:
type
ETrigError = class(EMathError);
function Tan(X: Extended): Extended;
begin
try
Result := Sin(X) / Cos(X);
except
on EMathError do
raise ETrigError.Create('Invalid argument to Tan');
end;
end;
Try...finally Statements
Sometimes you want to ensure that specific parts of an operation are
completed, whether or not the operation is interrupted by an exception. For
example, when a routine acquires control of a resource, it is often important that
the resource be released, regardless of whether the routine terminates normally.
In these situations, you can use a try...finally statement.
The following example shows how code that opens and processes a file can
ensure that the file is ultimately closed, even if an error occurs during execution:
Reset(F);
try
... // process file F
finally
CloseFile(F);
end;
If an exception is raised but not handled in the finally clause, that exception is
propagated out of the try...finally statement, and any exception already raised
in the try clause is lost. The finally clause should therefore handle all locally raised
exceptions, so as not to disturb propagation of other exceptions.
The SysUtils.Exception class has properties called Message and HelpContext that
can be used to pass an error description and a context ID for context-sensitive
Class and record helpers provide a way to extend a type, but they should not be
viewed as a design tool to be used when developing new code. For new code
you should always rely on normal class inheritance and interface
implementations.
Helper Syntax
The syntax for declaring a class helper is:
type
identifierName = class|record helper [(ancestor list)] for
TypeIdentifierName
memberList
end;
The ancestor list is optional. It can be specified only for class helper.
A helper type may not declare instance data, but class fields are allowed.
The visibility scope rules and memberList syntax are identical to that of ordinary
class and record types.
You can define and associate multiple helpers with a single type. However, only
zero or one helper applies in any specific location in source code. The helper
defined in the nearest scope will apply. Class or record helper scope is
determined in the normal Delphi fashion (for example, right to left in the unit's
uses clause).
type
TMyClass = class
procedure MyProc;
function MyFunc: Integer;
end;
...
procedure TMyClass.MyProc;
var X: Integer;
begin
X := MyFunc;
end;
...
type
TMyClassHelper = class helper for TMyClass
procedure HelloWorld;
function MyFunc: Integer;
end;
...
procedure TMyClassHelper.HelloWorld;
begin
Writeln(Self.ClassName); // Self refers to TMyClass type, not
TMyClassHelper
end;
...
var
X: TMyClass;
begin
X := TMyClass.Create;
X.MyProc; // Calls TMyClass.MyProc
X.HelloWorld; // Calls TMyClassHelper.HelloWorld
X.MyFunc; // Calls TMyClassHelper.MyFunc
Note that the class helper function MyFunc is called, because the class helper
takes precedence over the actual class type.
type
className = class [abstract | sealed] (ancestorType)
memberList
type
nestedTypeDeclaration
memberList
end;
The normal accessibility rules apply to nested types and their containing types. A
nested type can access an instance variable (field, property, or method) of its
container class, but it must have an object reference to do so. A nested type
can access class fields, class properties, and class static methods without an
object reference, but the normal Delphi visibility rules apply.
Nested types do not increase the size of the containing class. Creating an
instance of the containing class does not also create an instance of a nested
type. Nested types are associated with their containing classes only by the
context of their declaration.
type
TOuterClass = class
strict private
myField: Integer;
public
type
TInnerClass = class
public
myInnerField: Integer;
procedure innerProc;
end;
procedure outerProc;
end;
To implement the innerProc method of the inner class, you must qualify its name
with the name of the outer class. For example:
procedure TOuterClass.TInnerClass.innerProc;
begin
...
end;
To access the members of the nested type, use dotted notation as with regular
class member access. For example:
var
x: TOuterClass;
y: TOuterClass.TInnerClass;
begin
x := TOuterClass.Create;
x.outerProc;
...
y := TOuterClass.TInnerClass.Create;
y.innerProc;
Nested Constants
Constants can be declared in class types in the same manner as nested type
sections. Constant sections are terminated by the same tokens as nested type
sections, specifically, reserved words or visibility specifiers. Typed constants are
not supported, so you cannot declare nested constants of value types, such as
System.Currency, or System.TDateTime.
Nested constants can be of any simple type: ordinal, ordinal subranges, enums,
strings, and real types.
type
TMyClass = class
const
x = 12;
y = TMyClass.x + 23;
procedure Hello;
private
const
s = 'A string constant';
end;
begin
Writeln(TMyClass.y); // Writes the value of y, 35.
end.
The following table shows the Delphi operators that can be overloaded:
No operators other than those listed in the table may be defined on a class or
record.
The compiler will use an operator for a class or record provided that:
o For binary operators, one of the input parameters must be the class type.
o For unary operators, either the input parameter or the return value must
be the class type.
o For a logical operator and a bitwise operator using the same symbol, the
logical operator is used only when the operands are booleans. Since the
type of the class of this class operator is not a boolean, a logical operator
will only be used when the other operand is a boolean.
As a general rule, operators should not modify their operands. Instead, return a
new value, constructed by performing the operation on the parameters.
Overloaded operators are used most often in records (that is, value types).
type
typeName = record
class operator conversionOp(a: type): resultType;
class operator unaryOp(a: type): resultType;
class operator comparisonOp(a: type; b: type): Boolean;
class operator binaryOp(a: type; b: type): resultType;
end;
type
TMyRecord = record
class operator Add(a, b: TMyRecord): TMyRecord; // Addition of two
operands of type TMyRecord
class operator Subtract(a, b: TMyRecord): TMyRecord; // Subtraction of
type TMyRecord
class operator Implicit(a: Integer): TMyRecord; // Implicit
conversion of an Integer to type TMyRecord
class operator Implicit(a: TMyRecord): Integer; // Implicit
conversion of TMyRecordto Integer
class operator Explicit(a: Double): TMyRecord; // Explicit
conversion of a Double to TMyRecord
end;
var
x, y: TMyRecord;
begin
x := 12; // Implicit conversion from an Integer
y := x + x; // Calls TMyRecord.Add(a, b: TMyRecord): TMyRecord
b := b + 100; // Calls TMyRecord.Add(b, TMyRecord.Implicit(100))
end;
Code Samples
o RTL.ComplexNumbers Sample
Some standard routines are in units such as SysUtils, which must be listed in a uses
clause to make them available in programs. You cannot, however, list System in
a uses clause, nor should you modify the System unit or try to rebuild it explicitly.
Note: For new programs, you might want to use the File
Management classes and functions in the System.Classes and
System.SysUtils units. System.Classes.TStream and its descendent
classes are currently recommended for general file handling in
Delphi (for related routines, see Streams, Reader and Writers). For
text-file handling, TStreamReader and TStreamWriter are
recommended over calling Write and Writeln. API Categories Index
contains lists of related routines and classes.
FileSize Returns the current size of a file; not used for text files.
IOResult Returns an integer value that is the status of the last I/O function
performed.
Read Reads one or more values from a file into one or more variables.
Readln Does what Read does and then skips to beginning of next line in the
text file.
Writeln Does the same as Write, and then writes an end-of-line marker to the
text file.
A file variable is any variable whose type is a file type. There are three classes of
file: typed, text, and untyped. The syntax for declaring file types is given in File
types. Note that file types are only available on the Win32 platform.
Before a file variable can be used, it must be associated with an external file
through a call to the AssignFile procedure. An external file is typically a named
disk file, but it can also be a device, such as the keyboard or the display. The
external file stores the information written to the file or supplies the information
read from the file.
Once the association with an external file is established, the file variable must be
opened to prepare it for input or output. An existing file can be opened via the
Reset procedure, and a new file can be created and opened via the Rewrite
procedure. Text files opened with Reset are read-only and text files opened with
Rewrite and Append are write-only. Typed files and untyped files always allow
both reading and writing regardless of whether they were opened with Reset or
Rewrite.
Files are normally accessed sequentially. That is, when a component is read using
the standard procedure Read or written using the standard procedure Write, the
current file position moves to the next numerically ordered file component.
Typed files and untyped files can also be accessed randomly through the
standard procedure Seek, which moves the current file position to a specified
component. The standard functions FilePos and FileSize can be used to
determine the current file position and the current file size.
When a program completes processing a file, the file must be closed using the
standard procedure CloseFile. After a file is closed, its associated external file is
updated. The file variable can then be associated with another external file.
By default, all calls to standard I/O procedures and functions are automatically
checked for errors, and if an error occurs an exception is raised (or the program
You must call the IOResult function to clear an error, even if you aren't interested
in the error. If you do not clear an error and {$I-} is the current state, the next I/O
function call will fail with the lingering IOResult error.
Text Files
This section summarizes I/O using file variables of the standard type Text.
When a text file is opened, the external file is interpreted in a special way: It is
considered to represent a sequence of characters formatted into lines, where
each line is terminated by an end-of-line marker (a carriage-return character,
possibly followed by a line feed character). The type Text is distinct from the type
file of Char.
For text files, there are special forms of Read and Write that let you read and
write values that are not of type Char. Such values are automatically translated
to and from their character representation. For example, Read(F, I), where I is a
type Integer variable, reads a sequence of digits, interprets that sequence as a
decimal integer, and stores it in I.
There are two standard text file variables, System.Input and System.Output The
standard file variable System.Input is a read-only file associated with the
operating system's standard input (typically, the keyboard). The standard file
variable System.Output is a write-only file associated with the operating system's
standard output (typically, the display). Before an application begins executing,
System.Input and System.Output are automatically opened, as if the following
statements were executed:
AssignFile(Input, '');
Reset(Input);
AssignFile(Output, '');
Rewrite(Output);
Some of the standard I/O routines that work on text files do not need to have a
file variable explicitly given as a parameter. If the file parameter is omitted,
System.Input or System.Output is assumed by default, depending on whether the
If you do specify a file when calling one of the input or output routines that work
on text files, the file must be associated with an external file using AssignFile, and
opened using Reset, Rewrite, or Append. An error occurs if you pass a file that
was opened with Reset to an output-oriented procedure or function. An error
also occurs if you pass a file that was opened with Rewrite or Append to an
input-oriented procedure or function.
Untyped Files
Untyped files are low-level I/O channels used primarily for direct access to disk
files regardless of type and structuring. An untyped file is declared with the word
file and nothing more. For example:
For untyped files, the Reset and Rewrite procedures allow an extra parameter to
specify the record size used in data transfers. For historical reasons, the default
record size is 128 bytes. A record size of 1 is the only value that correctly reflects
the exact size of any file. (No partial records are possible when the record size is
1.)
Except for Read and Write, all typed-file standard procedures and functions are
also allowed on untyped files. Instead of Read and Write, two procedures called
BlockRead and BlockWrite are used for high-speed data transfers.
The four functions that define each device driver are Open, InOut, Flush, and
Close. The function header of each function is:
where DeviceFunc is the name of the function (that is, Open, InOut, Flush, or
Close). The return value of a device-interface function becomes the value
returned by IOResult. If the return value is zero, the operation was successful.
To associate the device-interface functions with a specific file, you must write a
customized Assign procedure. The Assign procedure must assign the addresses of
the four device-interface functions to the four function pointers in the text file
variable. In addition, it should store the fmClosed magic constant in the Mode
Assuming, for example, that the four device-interface functions are called
DevOpen, DevInOut, DevFlush, and DevClose, the Assign procedure might look
like this:
The device-interface functions can use the UserData field in the file record to
store private information. This field is not modified by the product file system at
any time.
The Open function prepares the file for input or output, according to the Mode
value. If Mode specified fmInOut (indicating that Open was called from
Append), it must be changed to fmOutput before Open returns.
Open is always called before any of the other device-interface functions. For
that reason, AssignDev only initializes the OpenFunc field, leaving initialization of
the remaining vectors up to Open. Based on Mode, Open can then install
pointers to either input- or output-oriented functions. This saves the InOut, Flush
functions and the CloseFile procedure from determining the current mode.
When Mode is fmOutput, the InOut function writes BufPos characters from
BufPtr^, and returns zero in BufPos.
If Mode is fmInput, the Flush function can store zero in BufPos and BufEnd to flush
the remaining (unread) characters in the buffer. This feature is seldom used.
If Mode is fmOutput, the Flush function can write the contents of the buffer
exactly like the InOut function, which ensures that text written to the device
appears on the device immediately. If Flush does nothing, the text does not
appear on the device until the buffer becomes full or the file is closed.
StrBufSize Returns the size of a character buffer allocated using StrAlloc or StrNew.
StrECopy Copies a string and returns a pointer to the end of the string.
StrLCat Concatenates two strings with a given maximum length of the resulting
string.
StrFmt Formats one or more values into a string with a given maximum length.
StrLIComp Compares two strings for a given maximum length without case sensitivity.
StrPos Returns a pointer to the first occurrence of a given substring within a string.
StrRscan Returns a pointer to the last occurrence of a given character within a string.
Wide-Character Strings
The System unit provides three functions, WideCharToString,
WideCharLenToString, and StringToWideChar, that can be used to convert null-
terminated wide character strings to single- or double-byte long strings.
Assignment will also convert between strings. For instance, the following are both
valid:
MyAnsiString := MyWideString;
MyWideString := MyAnsiString;
High Returns the highest value in the range of a type, array, or string.
Low Returns the lowest value in the range of a type, array, or string.
Round Returns the value of a real rounded to the nearest whole number.
UniqueString Ensures that a string has only one reference. (The string may be
copied to produce a single reference.)
Topics
o Libraries and Packages (Delphi)
o Packages (Delphi)
Delphi programs can call DLLs and shared objects written in other languages,
and applications written in other languages can call DLLs or shared objects
written in Delphi.
Before you can call routines defined in DLL or shared object, you must import
them. This can be done in two ways: by declaring an external procedure or
function, or by direct calls to the operating system. Whichever method you use,
the routines are not linked to your application until run time.
Delphi does not support importing variables from DLLs or shared objects.
Static Loading
The simplest way to import a procedure or function is to declare it using the
external directive. For example:
The delayed directive is useful in the case where the imported routines do not
exist on the target operating system on which the application is run. Statically
imported routines require that the operating system find and load the library
when the application is started. If the routine is not found in the loaded library, or
the library does not exist, the Operating System halts the execution of the
application. Using the delayed directive enables you to check, at run time,
whether the Operating System supports the required APIs; only then you can call
the imported routines.
Another potential use for the delayed directive is related to the memory footprint
of the application: decorating the less probably to be used routines, as delayed
may decrease the memory footprint of the application, because the libraries are
loaded only when required. The abusive use of delayed can damage the speed
performance of the program (as perceived by the end user).
Note: Trying to call a delayed routine that cannot be resolved results in a run-
time error (or an exception, if the SysUtils unit is loaded).
Dynamic Loading
You can access routines in a library through direct calls to Windows APIs,
including LoadLibrary, FreeLibrary, and GetProcAddress. They are also available
on OS X, Linux, and Android. These functions are declared in
Winapi.Windows.pas unit for Windows and in System.SysUtils.pas for other
platforms. In this case, use procedural-type variables to reference the imported
routines.
type
TTimeRec = record
Second: Integer;
Minute: Integer;
Hour: Integer;
end;
var
Time: TTimeRec;
Handle: HMODULE;
GetTime: TGetTime;
begin
Handle := LoadLibrary('libraryname');
if Handle <> 0 then
begin
@GetTime := GetProcAddress(Handle, 'GetTime');
if @GetTime <> nil then
begin
GetTime(Time);
with Time do
Writeln('The time is ', Hour, ':', Minute, ':', Second);
end;
FreeLibrary(Handle);
end;
end.
When you import routines this way, the library is not loaded until the code
containing the call to LoadLibrary executes. The library is later unloaded by the
call to FreeLibrary. This allows you to conserve memory and to run your program
even when some of the libraries it uses are not present.
o Global variables.
Only routines that a library explicitly exports are available for importing by other
libraries or programs. The following example shows a library with two exported
functions, Min and Max:
library MinMax;
function Min(X, Y: Integer): Integer; stdcall;
begin
if X < Y then Min := X else Min := Y;
end;
function Max(X, Y: Integer): Integer; stdcall;
begin
if X > Y then Max := X else Max := Y;
end;
exports
Min,
Max;
begin
end.
Libraries can be built from multiple units. In this case, the library source file is
frequently reduced to a uses clause, an exports clause, and the initialization
code. For example:
You can put exports clauses in the interface or implementation section of a unit.
Any library that includes such a unit in its uses clause automatically exports the
routines listed the unit's exports clauses without the need for an exports clause of
its own.
A routine is exported when it is listed in an exports clause, which has the form:
exports entry1, ..., entryn;
(Entries can also include the directive resident, which is maintained for backward
compatibility and is ignored by the compiler.)
On the Win32 platform, an index specifier consists of the directive index followed
by a numeric constant between 1 and 2,147,483,647. (For more efficient
programs, use low index values.) If an entry has no index specifier, the routine is
automatically assigned a number in the export table.
Note: Use of index specifiers, which are supported for backward compatibility only, is
discouraged and may cause problems for other development tools.
A name specifier consists of the directive name followed by a string constant. If
an entry has no name specifier, the routine is exported under its original declared
name, with the same spelling and case. Use a name clause when you want to
export a routine under a different name. For example:
exports
DoSomethingABC name 'DoSomething';
exports
Divide(X, Y: Integer) name 'Divide_Ints',
Divide(X, Y: Real) name 'Divide_Reals';
An exports clause can appear anywhere and any number of times in the
declaration part of a program or library, or in the interface or implementation
section of a unit. Programs seldom contain an exports clause.
Library initialization code can signal an error by setting the ExitCode variable to a
nonzero value. ExitCode is declared in the System unit and defaults to zero,
indicating successful initialization. If a library's initialization code sets ExitCode to
another value, the library is unloaded and the calling application is notified of
the failure. Similarly, if an unhandled exception occurs during execution of the
initialization code, the calling application is notified of a failure to load the
library.
library Test;
var
SaveDllProc: Pointer;
procedure LibExit(Reason: Integer);
begin
if Reason = DLL_PROCESS_DETACH then
begin
.
. // library exit code
.
end;
SaveDllProc(Reason); // call saved entry point procedure
end;
begin
.
. // library initialization code
.
SaveDllProc := DllProc; // save exit procedure chain
DllProc := @LibExit; // install LibExit exit procedure
end.
DllProc is called when the library is first loaded into memory, when a thread starts
or stops, or when the library is unloaded. The initialization parts of all units used by
a library are executed before the library's initialization code, and the finalization
parts of those units are executed after the library's entry point procedure.
A library can be used by several applications at once, but each application has
a copy of the library in its own process space with its own set of global variables.
For multiple libraries - or multiple instances of a library - to share memory, they
must use memory-mapped files. Refer to the your system documentation for
further information.
The DLLProc variable allows a library to monitor calls that the operating system
makes to the library entry point. This feature is normally used only by libraries that
support multithreading. DLLProc is used in multithreading applications. You
should use finalization sections, rather than exit procedures, for all exit behavior.
and assign the address of the procedure to the DLLProc variable. When the
procedure is called, it passes to it one of the following values.
DLL_PROCESS_DETACH Indicates that the library is detaching from the address space of
the calling process as a result of a clean exit or a call to
FreeLibrary.
In the body of the procedure, you can specify actions to take depending on
which parameter is passed to the procedure.
Generally, you should not let exceptions escape from your library. Delphi
exceptions map to the OS exception model.
If a library does not use the SysUtils unit, exception support is disabled. In this
case, when a runtime error occurs in the library, the calling application
terminates. Because the library has no way of knowing whether it was called
from a Delphi program, it cannot invoke the application's exit procedures; the
application is simply aborted and removed from memory.
Shared-Memory Manager
On Win32, if a DLL exports routines that pass long strings or dynamic arrays as
parameters or function results (whether directly or nested in records or objects),
ShareMem is the interface unit for the BORLANDMM.DLL memory manager, which
allows modules to share dynamically allocated memory. BORLANDMM.DLL must
be deployed with applications and DLLs that use ShareMem. When an
application or DLL uses ShareMem, its memory manager is replaced by the
memory manager in BORLANDMM.DLL.
Packages (Delphi)
Packages are typically the preferred way to export items other than simple
procedures and functions. Libraries should only be considered when
interopability with other programming is a requirement.
The following topics describe packages and various issues involved in creating
and compiling them.
o Naming packages
o Compiling packages
o Generated files
Understanding Packages
A package is a specially compiled library used by applications, the IDE, or both.
Packages allow you to rearrange where code resides without affecting the
source code. This is sometimes referred to as application partitioning.
On Win32, package files end with the .bpl (Borland package library) extension.
Ordinarily, packages are loaded statically when an applications starts. But you
can use the LoadPackage and UnloadPackage routines (in the SysUtils unit) to
load packages dynamically.
o a list of unit files contained by, or bound into, the package when it is
compiled. The package is essentially a wrapper for these source-code
units, which provide the functionality of the compiled package.
package packageName;
requiresClause;
containsClause;
end.
package DATAX;
requires
rtl,
contains Db, DBLocal, DBXpress, ... ;
end.
The requires clause lists other, external packages used by the package being
declared. It consists of the directive requires, followed by a comma-delimited list
The contains clause identifies the unit files to be compiled and bound into the
package. It consists of the directive contains, followed by a comma-delimited list
of unit names, followed by a semicolon. Any unit name may be followed by the
reserved word in and the name of a source file, with or without a directory path,
in single quotation marks; directory paths can be absolute or relative. For
example:
Naming packages
A compiled package involves several generated files. For example, the source
file for the package called DATAX is DATAX.DPK, from which the compiler
generates an executable and a binary image called
DATAX is used to refer to the package in the requires clauses of other packages,
or when using the package in an application. Package names must be unique
within a project.
All units included directly in a package's contains clause, or indirectly in the uses
clauses of those units, are bound into the package at compile time. The units
contained (directly or indirectly) in a package cannot be contained in any other
packages referenced in requires clause of that package.
Compiling Packages
Packages are ordinarily compiled from the IDE using .dpk files generated by the
Project Manager. You can also compile .dpk files directly from the command
line. When you build a project that contains a package, the package is implicitly
recompiled, if necessary.
Generated Files
The following table lists the files produced by the successful compilation of a
package.
BPL The runtime package. This file is a DLL on Win32 with special RAD Studio-
specific features. The base name for the package is the base name of the
dpk source file.
Directive Purpose
{$DESIGNONLY ON} Compiles the package for installation in the IDE. (Put in .dpk
file.)
{$RUNONLY ON} Compiles the package as runtime only. (Put in .dpk file.)
Including {$DENYPACKAGEUNIT ON} in source code prevents the unit file from
being packaged. Including {$G-} or {$IMPORTEDDATA OFF} may prevent a
package from being used in the same application with other packages.
Switch Purpose
LE path Specifies the directory where the compiled package file will
be placed.
LN path Specifies the directory where the package dcp or dcp file will
be placed.
Using the -$G- switch may prevent a package from being used in the same
application with other packages.
Topics
o Object Interfaces (Delphi)
o Implementing Interfaces
Interface Types
Interfaces, like classes, can be declared only in the outermost scope of a
program or unit, not in a procedure or function declaration. An interface type
declaration has the form:
o The memberList can include only methods and properties. Fields are not
allowed in interfaces.
o Since an interface has no fields, property read and write specifiers must
be methods.
Warning:
['{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}']
The TGUID and PGUID types, declared in the System unit, are used to manipulate
GUIDs.
type
PGUID = ^TGUID;
TGUID = packed record
D1: Cardinal;
D2: Word;
D3: Word;
D4: array[0..7] of Byte;
end;
or:
if Supports(Allocator, IID_IMalloc) then ...
Interface Properties
Properties declared in an interface are accessible only through expressions of
the interface type; they cannot be accessed through class-type variables.
Moreover, interface properties are visible only within programs where the
interface is compiled.
In an interface, property read and write specifiers must be methods, since fields
are not available.
Forward Declarations
An interface declaration that ends with the reserved word interface and a
semicolon, without specifying an ancestor, GUID, or member list, is a forward
declaration. A forward declaration must be resolved by a defining declaration
of the same interface within the same type declaration section. In other words,
between a forward declaration and its defining declaration, nothing can occur
except other type declarations.
Mutually derived interfaces are not allowed. For example, it is not legal to derive
IWindow from IControl and also derive IControl from IWindow.
Implementing Interfaces
Once an interface has been declared, it must be implemented in a class before
it can be used. The interfaces implemented by a class are specified in the
declaration of the class, after the name of the class ancestor.
For example:
type
TMemoryManager = class(TInterfacedObject, IMalloc, IErrorInfo)
// ...
end;
type
TInterfacedObject = class(TObject, IInterface)
protected
FRefCount: Integer;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
class function NewInstance: TObject; override;
property RefCount: Integer read FRefCount;
end;
Classes that implement interfaces can also be used as base classes. (The first
example above declares TMemoryManager as a direct descendent of
TInterfacedObject.) Every interface inherits from IInterface, and a class that
implements interfaces must implement the QueryInterface, _AddRef, and
_Release methods. TInterfacedObject in the unit System implements these
methods and is thus a convenient base from which to derive other classes that
implement interfaces.
or:
function interface.interfaceMethod = implementingMethod;
maps the Alloc and Free methods of IMalloc onto the Allocate and Deallocate
methods of TMemoryManager.
A class can also reimplement an entire interface that it inherits from an ancestor
class. This involves relisting the interface in the descendent class' declaration. For
example:
The implements directive must be the last specifier in the property declaration
and can list more than one interface, separated by commas. The delegate
property:
o Must have a read specifier. If the property uses a read method, that
method must use the default register calling convention and cannot be
dynamic (though it can be virtual) or specify the message directive.
The class you use to implement the delegated interface should derive from
System.TAggregatedObject.
type
IMyInterface = interface
procedure P1;
procedure P2;
end;
TMyImplClass = class
procedure P1;
procedure P2;
end;
TMyClass = class(TInterfacedObject, IMyInterface)
FMyImplClass: TMyImplClass;
property MyImplClass: TMyImplClass read FMyImplClass implements
IMyInterface;
procedure IMyInterface.P1 = MyP1;
procedure MyP1;
end;
procedure TMyImplClass.P1;
// ...
procedure TMyImplClass.P2;
// ...
procedure TMyClass.MyP1;
// ...
var
MyClass: TMyClass;
MyInterface: IMyInterface;
begin
MyClass := TMyClass.Create;
MyClass.FMyImplClass := TMyImplClass.Create;
MyInterface := MyClass;
MyInterface.P1; // calls TMyClass.MyP1;
MyInterface.P2; // calls TImplClass.P2;
end;
For example:
type
IAncestor = interface
end;
IDescendant = interface(IAncestor)
procedure P1;
end;
TSomething = class(TInterfacedObject, IDescendant)
procedure P1;
procedure P2;
end;
// ...
var
D: IDescendant;
A: IAncestor;
begin
D := TSomething.Create; // works!
A := TSomething.Create; // error
D.P1; // works!
D.P2; // error
end;
D: TSomething;
Interface Typecasts
An interface-type expression can be cast to Variant. If the interface is of type
IDispatch or a descendant, the resulting variant has the type code varDispatch.
Otherwise, the resulting variant has the type code varUnknown.
object as interface
An interface query returns nil if object is nil. Otherwise, it passes the GUID of the
interface to the QueryInterface method in object, raising an exception unless
QueryInterface returns zero. If QueryInterface returns zero (indicating that the
object's class implements the interface), the interface query returns an interface
reference to object.
var
LIntfRef: IInterface;
LObj: TInterfacedObject;
begin
{ Create an interfaced object and extract an interface from it. }
LIntfRef := TInterfacedObject.Create();
The above example shows how to obtain the original object from which the
interface reference was obtained. This technique is useful when possessing an
interface reference is simply not enough.
var
LIntfRef: IInterface;
LObj: TInterfacedObject;
begin
{ Create an interfaced object and extract an interface from it. }
LIntfRef := TInterfacedObject.Create();
try
{ Cast the interface to a TComponent. }
LObj := LIntfRef as TComponent;
except
Writeln('LIntfRef was not referencing a TComponent instance');
end;
end;
You can also perform normal type casting (unsafe) from an interface reference
to an object. Like in the case of object unsafe casting, this method does not
raise any exceptions. The difference between the unsafe object-to-object
casting and unsafe interface-to-object casting is that while the first returns a valid
pointer in case of incompatible types, the later returns nil. The example describes
the use of unsafe casting:
var
LIntfRef: IInterface;
LObj: TInterfacedObject;
begin
{ Create an interfaced object and extract an interface from it. }
LIntfRef := TInterfacedObject.Create();
To avoid potential nil references, use the is operator to verify whether the
interface reference was extracted from a given class:
Note: Make sure you are using Delphi-only objects when using the
unsafe casting or the as and is operators.
where
['{GUID}']
type
IStringsDisp = dispinterface
['{EE05DFE2-5549-11D0-9EA9-0020AF3D82DA}']
property ControlDefault[Index: Integer]: OleVariant dispid 0; default;
function Count: Integer; dispid 1;
property Item[Index: Integer]: OleVariant dispid 2;
procedure Remove(Index: Integer); dispid 3;
procedure Clear; dispid 4;
function Add(Item: OleVariant): Integer; dispid 5;
function _NewEnum: IUnknown; dispid -4;
end;
var
Word: Variant;
begin
Word := CreateOleObject('Word.Basic');
Word.FileNew('Normal');
Word.Insert('This is the first line'#13);
Word.Insert('This is the second line'#13);
Word.FileSaveAs('c:\temp\test.txt', 3);
end;
Variant arrays with an element type of varByte are the preferred method of
passing binary data between Automation controllers and servers. Such arrays
are subject to no translation of their data, and can be efficiently accessed using
the VarArrayLock and VarArrayUnlock routines.
Some Automation servers allow you to omit parameters from a method call,
accepting their default values. For example:
Word.FileSaveAs('test.doc');
Word.FileSaveAs('test.doc', 6);
Word.FileSaveAs('test.doc',,,'secret');
Word.FileSaveAs('test.doc', Password := 'secret');
Word.FileSaveAs(Password := 'secret', Name := 'test.doc');
Automation method call parameters can be of integer, real, string, Boolean, and
variant types. A parameter is passed by reference if the parameter expression
consists only of a variable reference, and if the variable reference is of type Byte,
Smallint, Integer, Single, Double, Currency, System.TDateTime, AnsiString,
WordBool, or Variant. If the expression is not of one of these types, or if it is not just
a variable, the parameter is passed by value. Passing a parameter by reference
to a method that expects a value parameter causes COM to fetch the value
from the reference parameter. Passing a parameter by value to a method that
expects a reference parameter causes an error.
Dual Interfaces
A dual interface is an interface that supports both compile-time binding and
runtime binding through Automation. Dual interfaces must descend from
IDispatch.
All methods of a dual interface (except from those inherited from IInterface and
IDispatch) must use the safecall convention, and all method parameter and
result types must be automatable. (The automatable types are Byte, Currency,
Real, Double, Real48, Integer, Single, Smallint, AnsiString, ShortString,
System/TDateTime, Variant, OleVariant, and WordBool.)
Topics
o Memory Management
Memory Management
This help topic describes the two memory managers that are used on the various
target platforms, and briefly describes memory issues of variables.
The following table lists the default memory manager for each platform.
For Win32 and Win64, the default FastMM Memory Manager is optimized for
applications that allocate large numbers of small- to medium-sized blocks, as is
typical for object-oriented applications and applications that process string
data. The Memory Manager is optimized for efficient operation (high speed and
low memory overhead) in single and multi-threaded applications. Other memory
managers, such as the implementations of GlobalAlloc, LocalAlloc, and private
heap support in Windows, typically do not perform well in such situations, and
would slow down an application if they were used directly.
To ensure the best performance, the Memory Manager interfaces directly with
the virtual memory API (the >VirtualAlloc and VirtualFree functions).
For Win32, the Memory Manager supports a user mode address space up to
2GB.
For Win64, the Memory Manager supports a user mode address space up to
16EiB in speculation.
For Win32 and Win64, the Memory Manager employs an algorithm that
anticipates future block reallocations, reducing the performance impact usually
associated with such operations. The reallocation algorithm also helps reduce
address space fragmentation. The memory manager provides a sharing
mechanism that does not require the use of an external DLL.
AllocMem calloc
FreeMem free
GetMem malloc
ReallocMem realloc
Variables
Global variables are allocated on the application data segment and persist for
the duration of the program. Local variables (declared within procedures and
functions) reside in the stack of an application. Each time a procedure or
function is called, it allocates a set of local variables; on exit, the local variables
are disposed of. Compiler optimization may eliminate variables earlier.
If a Win32 application requires more stack space than specified by the minimum
stack size, additional memory is automatically allocated in 4K increments. If
allocation of additional stack space fails, either because more memory is not
available or because the total size of the stack would exceed the maximum
stack size, an EStackOverflow exception is raised. (Stack overflow checking is
completely automatic. The $S compiler directive, which originally controlled
overflow checking, is maintained for backward compatibility.)
Dynamic variables created with the GetMem or New procedure are heap-
allocated and persist until they are deallocated with FreeMem or Dispose.
Integer Types
Integer values have the following internal representation in Delphi.
Values of unsigned integer types always are positive and do not involve a Sign
bit as do signed integer types. All bits of unsigned integer types occupy by the
magnitude of the value and have no other meaning.
Byte, UInt8
Byte and UInt8 are 1-byte (8-bit) unsigned positive integer numbers. The
Magnitude occupies all 8-bits.
For example:
Example 1 Example 2
ShortInt, Int8
Shortint and Int8 are 1-byte (8-bit) signed integer numbers. The sign bit' occupies
the most significant 7-th bit, the Magnitude or two's complement occupies other
7 bits.
Int64
Int64 are 8-byte (64-bit) signed integer numbers.
Note: 32-bit platforms in RAD Studio include 32-bit Windows, OSX32, 32-bit iOS,
and Android.
The internal data format of an integer subrange type variable depends on its
minimum and maximum bounds:
o If both bounds are within the range -128..127 (ShortInt), the variable is
stored as a signed byte.
o If both bounds are within the range 0..255 (Byte), the variable is stored as
an unsigned byte.
o If both bounds are within the range -32768..32767 (SmallInt), the variable is
stored as a signed word.
o If both bounds are within the range 0..65535 (Word), the variable is stored
as an unsigned word.
o If both bounds are within the range -2^63..2^63-1 (Int64 and LongInt on
64-bit iOS platforms), the variable is stored as a signed quadruple word.
o If both bounds are within the range 0..2^64-1 (UInt64 and LongWord on
64-bit iOS platforms), the variable is stored as an unsigned quadruple
word.
Character Types
On the 32-bit and 64-bit platforms:
Boolean Types
A Boolean type is stored as a Byte, a ByteBool is stored as a Byte, a WordBool
type is stored as a Word, and a LongBool is stored as a Longint.
A Boolean can assume the values 0 (False) and 1 (True). ByteBool, WordBool, and
LongBool types can assume the values 0 (False) or nonzero (True).
Enumerated Types
An enumerated type is stored as an unsigned byte if the enumeration has no
more than 256 values and the type was declared in the {$Z1} state (the default).
If an enumerated type has more than 256 values, or if the type was declared in
the {$Z2} state, it is stored as an unsigned word. If an enumerated type is
declared in the {$Z4} state, it is stored as an unsigned double-word.
Real Types
The real types store the binary representation of a sign (+ or -), an exponent, and
a significand. A real value has the form
where the significand has a single bit to the left of the binary decimal point
(that is, 0 <= significand < 2).
In the images that follow, the most significant bit is always on the left, and the
least significant bit, on the right. The numbers at the top indicate the width (in
bits) of each field, with the leftmost items stored at the highest addresses. For
example, for a Real48 value, e is stored in the first byte, f in the following five
bytes, and s in the most significant bit of the last byte.
s f e
If e = 0, then v = 0.
The Real48 type cannot store denormals, NaNs, and infinities (Inf). Denormals
become zero when stored in a Real48, while NaNs and infinities produce an
overflow error if an attempt is made to store them in a Real48.
s e f
On 32-bit and 64-bit platforms, an 8-byte (64-bit) Double number is divided into
three fields.
1 11 52
s e f
s e i f
However, on the 64-bit Intel platform and ARM platform, the Extended type is an
alias for Double, which is only 8 bytes. This difference can adversely affect
numeric precision in floating-point operations. For more information, see Delphi
Considerations for Multi-Device Applications. On MAC OS X systems, the size of
Extended is 16 bytes in order to be compatible with BCCOSX.
Pointer Types
On 32-bit platforms, a pointer type is stored in 4 bytes as a 32-bit address.
The length byte and the characters are considered unsigned values. The
maximum string length is 255 characters plus a length byte (string[255]).
String Data
CodePag ElementSiz ReferenceCou
Field Length (ElementSize Null Term
e e nt
d)
Numbers in the Offset row show offsets of fields, describing the string contents,
from the string pointer, which points to the String Data field (offset = 0),
containing a block of memory that contains the actual string values.
For string literals, the compiler generates a memory block with the same layout
as a dynamically allocated string, but with a reference count of -1. String
var
destination : String;
source : String;
...
destination := 'qwerty'; // reference count for the newly-created block of
memory (containing the 'qwerty' string) pointed at by the "destination"
variable is now 1
...
source := 'asdfgh'; // reference count for the newly-created block of memory
(containing the 'asdfgh' string) pointed at by the "destination" variable is
now 1
destination := source; // reference count for the memory block containing the
'asdfgh' string is now 2, and since reference count for the block of memory
containing the 'qwerty' string is now 0, the memory block is deallocated.
If the source reference count is not -1, it is incremented and the destination will
point to it.
var
destination, destination2, destination3: String;
destination := 'Sample String'; //reference count for the newly-created block
of memory containing 'Sample string' is 1.
destination2 := destination; //reference count for the block of memory
containing 'Sample string' is now 2.
destination3 := destination; //reference count for the block of memory
containing 'Sample string' is now 3.
The string length is the number of bytes, so it is twice the number of wide
characters contained in the string.
The NULL character at the end of a wide string memory block is automatically
maintained by the compiler and the built-in string handling routines. This makes it
possible to typecast a wide string directly to a null-terminated string.
Set Types
A set is a bit array where each bit indicates whether an element is in the set or
not. The maximum number of elements in a set is 256, so a set never occupies
more than 32 bytes. The number of bytes occupied by a particular set is equal to
(Max div 8) - (Min div 8) + 1
where Max and Min are the upper and lower bounds of the base type of the set.
The byte number of a specific element E is
(E div 8) - (Min div 8)
where E denotes the ordinal value of the element. When possible, the compiler
stores sets in CPU registers, but a set always resides in memory if it is larger than
the platform-dependent integer type or if the program contains code that takes
the address of the set.
Record Types
When a record type is declared in the {$A+} state (the default), and when the
declaration does not include a packed modifier, the type is an unpacked
record type, and the fields of the record are aligned for efficient access by the
CPU, and according to the platform. The alignment is controlled by the type of
each field. Every data type has an inherent alignment, which is automatically
computed by the compiler. The alignment can be 1, 2, 4, or 8, and represents
the byte boundary on which a value of the type must be stored in order to
provide the most efficient access. The table below lists the alignments for all data
types.
Real types 2 for Real48, 4 for Single, 8 for Double and Extended
File Types
File types are represented as records. Typed files and untyped files occupy 592
bytes on 32-bit platforms and 616 bytes on 64-bit platforms, which are laid out as
follows:
type
TFileRec = packed record
Handle: NativeInt;
Mode: word;
Flags: word;
case Byte of
0: (RecSize: Cardinal);
1: (BufSize: Cardinal;
BufPos: Cardinal;
BufEnd: Cardinal;
BufPtr: _PAnsiChr;
OpenFunc: Pointer;
InOutFunc: Pointer;
FlushFunc: Pointer;
CloseFunc: Pointer;
UserData: array[1..32] of Byte;
Name: array[0..259] of WideChar; );
end;
type
TTextBuf = array[0..127] of Char;
TTextRec = packed record
Handle: NativeInt;
Mode: word;
Flags: word;
BufSize: Cardinal;
BufPos: Cardinal;
BufEnd: Cardinal;
BufPtr: _PAnsiChr;
OpenFunc: Pointer;
InOutFunc: Pointer;
FlushFunc: Pointer;
CloseFunc: Pointer;
UserData: array[1..32] of Byte;
Name: array[0..259] of WideChar;
Buffer: TTextBuf; //
CodePage: Word;
MBCSLength: ShortInt;
MBCSBufPos: Byte;
case Integer of
0: (MBCSBuffer: array[0..5] of _AnsiChr);
1: (UTF16Buffer: array[0..2] of WideChar);
end;
Handle contains the handle of the file (when the file is open).
const
fmClosed = $D7B0;
fmInput= $D7B1;
fmOutput = $D7B2;
fmInOut= $D7B3;
where fmClosed indicates that the file is closed, fmInput and fmOutput indicate a
text file that has been reset (fmInput) or rewritten (fmOutput), fmInOut indicates a
typed or untyped file that has been reset or rewritten. Any other value indicates
that the file variable is not assigned (and hence not initialized).
The UserData field is available for user-written routines to store data in.
For typed files and untyped files, RecSize contains the record length in bytes,
and the Private field is unused but reserved.
For text files, BufPtr is a pointer to a buffer of BufSize bytes, BufPos is the index of
the next character in the buffer to read or write, and BufEnd is a count of valid
characters in the buffer. OpenFunc, InOutFunc, FlushFunc, and CloseFunc are
Note: For using the UnicodeString type (the default Delphi string
type), the various stream types in the Classes unit (TFileStream,
TStreamReader, TStreamWriter, and so forth) are more useful, since
the older file types have limited Unicode functionality, particularly
the old text file type.
Procedural Types
On the 32-bit platform, a procedure pointer is stored as a 32-bit pointer to the
entry point of a procedure or function. A method pointer is stored as a 32-bit
pointer to the entry point of a method, followed by a 32-bit pointer to an object.
Class Types
On the 32-bit platforms (Win32, OSX, iOS and Android), a class-type value is
stored as a 32-bit pointer to an instance of the class (and as a 64-bit pointer on
the 64-bit platform), which is called an object. The internal data format of an
object resembles that of a record. The fields of the object are stored in order of
declaration as a sequence of contiguous variables. Fields are always aligned,
corresponding to an unpacked record type. Therefore, the alignment
corresponds to the largest alignment of the fields in the object. Any fields
inherited from an ancestor class are stored before the new fields defined in the
descendent class.
On the 32-bit platforms, the first 4-byte field of every object (the first 8-byte field
on the 64-bit platform) is a pointer to the virtual method table (VMT) of the class.
There is exactly one VMT per class (not one per object); distinct class types, no
matter how similar, never share a VMT. VMTs are built automatically by the
compiler, and are never directly manipulated by a program. Pointers to VMTs,
which are automatically stored by constructor methods in the objects they
create, are also never directly manipulated by a program.
The layout of a VMT is shown in the following table. On the 32-bit platforms, at
positive offsets, a VMT consists of a list of 32-bit method pointers (64-bit method
pointers on the 64-bit platform)--one per user-defined virtual method in the class
type--in order of declaration. Each slot contains the address of the
Variant Types
Variants rely on boxing and unboxing of data into an object wrapper, as well as
Delphi helper classes to implement the variant-related RTL functions.
The TVarData type represents the internal structure of a Variant variable (on
Windows, this is identical to the Variant type used by COM and the Win32 API).
The TVarData type can be used in typecasts of Variant variables to access the
internal structure of a variable. The TVarData record contains the following fields:
o The VType field of the TVarType type has the Word (16-bit) size. VType
contains the type code of the variant in the lower 12 bits (the bits defined
by the varTypeMask = $FFF constant). In addition, the varArray = $2000
bit may be set to indicate that the variant is an array, and the varByRef (=
$4000) bit may be set to indicate that the variant contains a reference as
opposed to a value.
o The Reserved1, Reserved2, and Reserved3 (Word size) fields are unused.
o If the varByRef bit is set, the variant contains a reference to a value of the
type given by the varTypeMask and varArray bits in the VType field.
The varString type code is private. Variants containing a varString value should
never be passed to a non-Delphi function. On the Windows platform, Delphi's
Automation support automatically converts varString variants to varOleStr
variants before passing them as parameters to external functions.
o Passing Parameters.
Passing Parameters
Parameters are transferred to procedures and functions via CPU registers or the
stack, depending on the routine's calling convention. For information about
calling conventions, see the topic on Calling Conventions.
o Sets, records, and static arrays of 1, 2, or 4 bytes are passed as 8-bit, 16-bit,
and 32bit values. Larger sets, records, and static arrays are passed as 32-
bit pointers to the value. An exception to this rule is that records are
always passed directly on the stack under the cdecl, stdcall, and safecall
conventions; the size of a record passed this way is rounded upward to
the nearest double-word boundary.
When two parameters are passed on the stack, each parameter occupies a
multiple of 4 bytes (a whole number of double words). For an 8-bit or 16-bit
parameter, even though the parameter occupies only a byte or a word, it is
passed as a double word. The contents of the unused parts of the double word
are undefined.
When working with the MMX and XMM instructions, be sure to preserve the
values of the xmm and mm registers. Delphi functions are invoked with the
assumption that the x87 FPU data registers are available for use by x87 floating
point instructions. That is, the compiler assumes that the EMMS/FEMMS instruction
has been called after MMX operations. Delphi functions do not make any
assumptions about the state and content of xmm registers. They do not
guarantee that the content of xmm registers is unchanged.
o Ordinal results are returned, when possible, in a CPU register. Bytes are
returned in AL, words are returned in AX, and double-words are returned
in EAX.
o For a string, dynamic array, method pointer, or variant result, the effects
are the same as if the function result were declared as an additional var
parameter following the declared parameters. In other words, the caller
passes an additional 32-bit pointer that points to a variable in which to
return the function result.
o For static-array, record, and set results, if the value occupies one byte it is
returned in AL; if the value occupies two bytes it is returned in AX; and if
the value occupies four bytes it is returned in EAX. Otherwise, the result is
returned in an additional var parameter that is passed to the function
after the declared parameters.
o Under the pascal convention, Self behaves as if it were declared after all
other parameters (including the additional var parameter sometimes
passed for a function result). It is therefore pushed last, ending up at a
lower address than all other parameters.
A value of False in the flag parameter of a constructor call indicates that the
constructor was invoked through an instance object or using the inherited
keyword. In this case, the constructor behaves like an ordinary method. A value
of True in the flag parameter of a constructor call indicates that the constructor
A value of False in the flag parameter of a destructor call indicates that the
destructor was invoked using the inherited keyword. In this case, the destructor
behaves like an ordinary method. A value of True in the flag parameter of a
destructor call indicates that the destructor was invoked through an instance
object. In this case, the destructor deallocates the instance given by Self just
before returning.
The flag parameter behaves as if it were declared before all other parameters.
Under the register convention, it is passed in the DL register. Under the pascal
convention, it is pushed before all other parameters. Under the cdecl, stdcall,
and safecall conventions, it is pushed just before the Self parameter.
Units as well as programs can install exit procedures. A unit can install an exit
procedure as part of its initialization code, relying on the procedure to close files
or perform other clean-up tasks.
var
ExitSave: Pointer;
procedure MyExit;
begin
ExitProc := ExitSave; // always restore old vector first
.
.
.
end;
begin
ExitSave := ExitProc;
ExitProc := @MyExit;
.
.
.
end.
On entry, the code saves the contents of ExitProc in ExitSave, then installs the
MyExit procedure. When called as part of the termination process, the first thing
MyExit does is reinstall the previous exit procedure.
The termination routine in the runtime library keeps calling exit procedures until
ExitProc becomes nil. To avoid infinite loops, ExitProc is set to nil before every call,
so the next exit procedure is called only if the current exit procedure assigns an
address to ExitProc. If an error occurs in an exit procedure, it is not called again.
An exit procedure can learn the cause of termination by examining the ExitCode
integer variable and the ErrorAddr pointer variable. In case of normal
termination, ExitCode is zero and ErrorAddr is nil. In case of termination through a
call to Halt, ExitCode contains the value passed to Halt and ErrorAddr is nil. In
case of termination due to a runtime error, ExitCode contains the error code and
ErrorAddr contains the address of the invalid statement.
The last exit procedure (the one installed by the runtime library) closes the Input
and Output files. If ErrorAddr is not nil, it outputs a runtime error message. To
output your own runtime error message, install an exit procedure that examines
ErrorAddr and outputs a message if it's not nil; before returning, set ErrorAddr to
nil so that the error is not reported again by other exit procedures.
Once the runtime library has called all exit procedures, it returns to the operating
system, passing the value stored in ExitCode as a return code.
Topics
o Using Inline Assembly Code
o Assembler Syntax
o Assembly Expressions
o Supports all instructions found in the Intel Pentium 4, Intel MMX extensions,
Streaming SIMD Extensions (SSE), and the AMD Athlon (including 3D Now!).
As an alternative to the built-in assembler, you can link to object files that
contain external procedures and functions. See the topic External Declarations
for more information. If you have external assembly code that you want to use in
your applications, you should consider rewriting it in the Delphi language or
minimally reimplement it using the inline assembler.
However, inline assembly is not supported by the Delphi compilers for the iOS
device and Android device.
The reserved word inline and the directive assembler are maintained for
backward compatibility only. They have no effect on the compiler.
32-bit
In general, the rules of register use in an asm statement are the same as those of
an external procedure or function. An asm statement must preserve the EDI, ESI,
ESP, EBP, and EBX registers, but can freely modify the EAX, ECX, and EDX registers.
On entry to an asm statement, EBP points to the current stack frame and ESP
points to the top of the stack. Except for ESP and EBP, an asm statement can
assume nothing about register contents on entry to the statement.
64-bit
In line with the x64 Application Binary Interface (ABI), the contents of the
following registers must be preserved and restored within inline assembly
functions: R12, R13, R14, R15, RDI, RSI, RBX, RBP, RSP, XMM4, XMM5, XMM6, XMM7,
XMM8, XMM8, XMM9, XMM10, XMM11, XMM12, XMM13, XMM14, and XMM15.
The first four parameters to inline assembler functions are passed via RCX, RDX,
R8, and R9 respectively, except for floating-point arguments which use XMMO,
XMM1, XMM2, XMM3. The math coprocessor is not normally used from x64 code.
Registers used for function parameters can be modified freely.
{$IFDEF CPUX86}
asm
// ...
end;
{$ENDIF CPUX86}
{$IFDEF CPUX64}
asm
// ...
end;
{$ENDIF CPUX64}
Assembler Syntax
The following material describes the elements of the assembler syntax.
Statements
This syntax of an assembly statement is:
Labels
Labels are used in built-in assembly statements as they are in the Delphi
language by writing the label and a colon before a statement. There is no limit to
a label's length. As in Delphi, labels must be declared in a label declaration part
in the block containing the asm statement. The one exception to this rule is local
labels.
Local labels are labels that start with an at-sign (@). They consist of an at-sign
followed by one or more letters, digits, underscores, or at-signs. Use of local labels
is restricted to asm statements, and the scope of a local label extends from the
asm reserved word to the end of the asm statement that contains it. A local
label doesn't have to be declared.
Instruction Opcodes
The built-in assembler supports all of the Intel-documented opcodes for general
application use. Note that operating system privileged instructions may not be
supported. Specifically, the following families of instructions are supported:
o IA-32
Pentium family
Pentium III
Pentium 4
o Intel 64
In addition, the built-in assembler supports the following instruction set extensions
Jumps to the entry points of procedures and functions are always near.
Directives
The built-in assembler supports three assembly define directives: DB (define byte),
DW (define word), and DD (define double word). Each generates data
corresponding to the comma-separated operands that follow the directive.
Directive Description
The data generated by the DB, DW, and DD directives is always stored in the
code segment, just like the code generated by other built-in assembly
asm
DB FFH { One byte }
DB 0.99 { Two bytes }
DB 'A' { Ord('A') }
DB 'Hello world...',0DH,0AH { String followed by CR/LF }
DB 12,'string' { {{Delphi}} style string }
DW 0FFFFH { One word }
DW 0,9999 { Two words }
DW 'A' { Same as DB 'A',0 }
DW 'BA' { Same as DB 'A','B' }
DW MyVar { Offset of MyVar }
DW MyProc { Offset of MyProc }
DD 0FFFFFFFFH { One double-word }
DD 0,999999999 { Two double-words }
DD 'A' { Same as DB 'A',0,0,0 }
DD 'DCBA' { Same as DB 'A','B','C','D' }
DD MyVar { Pointer to MyVar }
DD MyProc { Pointer to MyProc }
end;
The built-in assembler does not support such variable declarations. The only kind
of symbol that can be defined in an inline assembly statement is a label. All
variables must be declared using Delphi syntax; the preceding construction can
be replaced by:
var
ByteVar: Byte;
WordVar: Word;
IntVar: Integer;
// …
asm
MOV AL,ByteVar
MOV BX,WordVar
MOV ECX,IntVar
end;
The second instruction will generate a move with an address size override prefix
and a 16-bit displacement ($1234).
SMALL can be used to save space. The following example generates an address
size override and a 2-byte address (in total three bytes):
as opposed to:
MOV EAX, [123]
which will generate no address size override and a 4-byte address (in total four
bytes).
Two additional directives allow assembly code to access dynamic and virtual
methods: VMTOFFSET and DMTINDEX.
VMTOFFSET retrieves the offset in bytes of the virtual method pointer table entry
of the virtual method argument from the beginning of the virtual method table
(VMT). This directive needs a fully specified class name with a method name as a
parameter (for example, TExample.VirtualMethod), or an interface name and an
interface method name.
DMTINDEX retrieves the dynamic method table index of the passed dynamic
method. This directive also needs a fully specified class name with a method
name as a parameter, for example, TExample.DynamicMethod. To invoke the
dynamic method, call System.@CallDynaInst with the (E)SI register containing the
value obtained from DMTINDEX.
TMyClass = class
procedure x; message MYMESSAGE;
end;
program Project2;
type
TExample = class
procedure DynamicMethod; dynamic;
procedure VirtualMethod; virtual;
end;
procedure TExample.DynamicMethod;
begin
end;
procedure TExample.VirtualMethod;
begin
end;
end;
var
e: TExample;
begin
e := TExample.Create;
try
CallDynamicMethod(e);
CallVirtualMethod(e);
finally
e.Free;
end;
end.
8-bit CPU
AH, AL, BH, BL, CH, CL, DH, DL (general purpose registers);
registers
16-bit CPU AX, BX, CX, DX (general purpose registers); DI, SI, SP, BP (index registers);
registers CS, DS, SS, ES (segment registers); IP (instruction pointer)
32-bit CPU EAX, EBX, ECX, EDX (general purpose registers); EDI, ESI, ESP, EBP (index
registers registers); FS, GS (segment registers); EIP
MMX FPU
mm0, ..., mm7
registers
Intel 64
RAX, RBX, ...
registers
Operators NOT, AND, OR, XOR; SHL, SHR, MOD; LOW, HIGH; OFFSET, PTR, TYPE
VMTOFFSET, DMTINDEX
SMALL, LARGE
var
Ch: Char;
// …
asm
MOV CH, 1
end;
loads 1 into the CH register, not into the Ch variable. To access a user-defined
symbol with the same name as a reserved word, you must use the ampersand
(&) override operator:
MOV&Ch, 1
Assembly Expressions
The built-in assembler evaluates all expressions as 32-bit integer values. It doesn't
support floating-point and string values, except string constants.
Expressions are built from expression elements and operators, and each
expression has an associated expression class and expression type.
const
X = 10;
Y = 20;
var
Z: Integer;
asm
MOV Z,X+Y
end;
the built-in assembler cannot compute the value of X + Y at compile time. In this
case, to move the sum of X and Y into Z you would use:
asm
MOV EAX,X
ADD EAX,Y
MOV Z,EAX
end;
asm
MOV EAX,X+4
end;
this code doesn't load the value of X plus 4 into AX; instead, it loads the value of
a word stored four bytes beyond X. The correct way to add 4 to the contents of
X is:
asm
MOV EAX,X
ADD EAX,4
end;
Expression Elements
The elements of an expression are constants, registers, and symbols.
Numeric Constants
Numeric constants must be integers, and their values must be between
2,147,483,648 and 4,294,967,295.
By default, numeric constants use decimal notation, but the built-in assembler
also supports binary, octal, and hexadecimal. Binary notation is selected by
writing a B after the number, octal notation by writing an O after the number,
and hexadecimal notation by writing an H after the number or a $ before the
number.
String Constants
String constants must be enclosed in single or double quotation marks. Two
consecutive quotation marks of the same type as the enclosing quotation marks
count as only one character. Here are some examples of string constants:
'Z'
'Delphi'
'Windows'
"That's all folks"
'"That''s all folks," he said.'
'100'
'"'
"'"
String constants of any length are allowed in DB directives, and cause allocation
of a sequence of bytes containing the ASCII values of the characters in the
string. In all other cases, a string constant can be no longer than four characters
and denotes a numeric value which can participate in an expression. The
numeric value of a string constant is calculated as:
where Ch1 is the rightmost (last) character and Ch4 is the leftmost (first)
character. If the string is shorter than four characters, the leftmost characters are
assumed to be zero. The following table shows string constants and their numeric
values.
'a' 00000061H
'ba' 00006261H
'cba' 00636261H
'dcba' 64636261H
'a' * 2 000000E2H
'a'-'A' 00000020H
Registers
The following reserved symbols denote CPU registers in the inline assembler:
CPU registers
Category Identifiers
8-bit CPU
AH, AL, BH, BL, CH, CL, DH, DL (general purpose registers);
registers
16-bit CPU AX, BX, CX, DX (general purpose registers); DI, SI, SP, BP (index registers);
registers CS, DS, SS, ES (segment registers); IP (instruction pointer)
32-bit CPU EAX, EBX, ECX, EDX (general purpose registers); EDI, ESI, ESP, EBP (index
registers registers); FS, GS (segment registers); EIP
MMX FPU
mm0, ..., mm7
registers
Intel 64
RAX, RBX, ...
registers
x64 CPU General purpose registers, x86 FPU data registers, and x64 SSE data registers
The base registers (BX and BP) and the index registers (SI and DI) can be written
within square brackets to indicate indexing. Valid base/index register
combinations are [BX], [BP], [SI], [DI], [BX+SI], [BX+DI], [BP+SI], and [BP+DI]. You
can also index with all the 32-bit registersfor example, [EAX+ECX], [ESP], and
[ESP+EAX+5].
The segment registers (ES, CS, SS, DS, FS, and GS) are supported, but segments
are normally not useful in 32-bit applications.
Symbols
The built-in assembler allows you to access almost all Delphi identifiers in
assembly language expressions, including constants, types, variables,
procedures, and functions. In addition, the built-in assembler implements the
special symbol @Result, which corresponds to the Result variable within the body
of a function. For example, the function:
The following table summarizes the kinds of symbol that can be used in asm
statements.
MOV EAX,Count
The built-in assembler treats var parameters as a 32-bit pointers, and the size of a
var parameter is always 4. The syntax for accessing a var parameter is different
from that for accessing a value parameter. To access the contents of a var
parameter, you must first load the 32-bit pointer and then access the location it
points to. For example:
Identifiers can be qualified within asm statements. For example, given the
declarations:
type
TPoint = record
X, Y: Integer;
end;
TRect = record
A, B: TPoint;
end;
var
P: TPoint;
R: TRect;
A type identifier can be used to construct variables on the fly. Each of the
following instructions generates the same machine code, which loads the
contents of [EDX] into EAX.
Expression Classes
The built-in assembler divides expressions into three classes: registers, memory
references, and immediate values.
Expressions that aren't registers and aren't associated with memory locations are
immediate values. This group includes Delphi's untyped constants and type
identifiers.
const
Start = 10;
var
Count: Integer;
// …
asm
MOV EAX,Start { MOV EAX,xxxx }
MOV EBX,Count { MOV EBX,[xxxx] }
MOV ECX,[Start] { MOV ECX,[xxxx] }
MOV EDX,OFFSET Count { MOV EDX,xxxx }
end;
Because Start is an immediate value, the first MOV is assembled into a move
immediate instruction. The second MOV, however, is translated into a move
memory instruction, as Count is a memory reference. In the third MOV, the
brackets convert Start into a memory reference (in this case, the word at offset
10 in the data segment). In the fourth MOV, the OFFSET operator converts Count
into an immediate value (the offset of Count in the data segment).
The brackets and OFFSET operator complement each other. The following asm
statement produces identical machine code to the first two lines of the previous
asm statement:
asm
MOV EAX,OFFSET [Start]
MOV EBX,[OFFSET Count]
end;
The built-in assembler allows you to carry out any operation on an absolute
value, but it restricts operations on relocatable values to addition and
subtraction of constants.
var
QuitFlag: Boolean;
OutBufPtr: Word;
// …
asm
MOV AL,QuitFlag
MOV BX,OutBufPtr
end;
the assembler checks that the size of QuitFlag is one (a byte), and that the size of
OutBufPtr is two (a word). The instruction:
MOV DL,OutBufPtr
These MOV instructions all refer to the first (least significant) byte of the OutBufPtr
variable.
The built-in assembler permits these instructions, because the expression [Buffer]
has no type. [Buffer] means "the contents of the location indicated by Buffer,"
and the type can be determined from the first operand (byte for AL, word for
CX, and double-word for EDX).
In cases where the type can't be determined from another operand, the built-in
assembler requires an explicit typecast. For example:
The following table summarizes the predefined type symbols that the built-in
assembler provides in addition to any currently declared Delphi types.
Symbol Type
BYTE 1
WORD 2
DWORD 4
QWORD 8
TBYTE 10
Expression Operators
The built-in assembler provides a variety of operators. Precedence rules are
different from that of the Delphi language; for example, in an asm statement,
AND has lower precedence than the addition and subtraction operators. The
following table lists the built-in assembler's expression operators in decreasing
order of precedence.
& highest
+, - unary + and -
. Structure member selector. The result is the sum of the expression before the
period and the expression after the period, with the type of the expression
after the period. Symbols belonging to the scope identified by the expression
before the period can be accessed in the expression after the period.
HIGH Returns the high-order 8 bits of the word-sized expression following the
operator. The expression must be an absolute immediate value.
LOW Returns the low-order 8 bits of the word-sized expression following the
operator. The expression must be an absolute immediate value.
+ Unary plus. Returns the expression following the plus with no changes. The
expression must be an absolute immediate value.
- Unary minus. Returns the negated value of the expression following the minus.
The expression must be an absolute immediate value.
- Subtraction. The first expression can have any class, but the second
expression must be an absolute immediate value. The result has the same
class as the first expression.
: Segment override. Instructs the assembler that the expression after the colon
belongs to the segment given by the segment register name (CS, DS, SS, FS,
GS, or ES) before the colon. The result is a memory reference with the value of
the expression after the colon. When a segment override is used in an
instruction operand, the instruction is prefixed with an appropriate segment-
override prefix instruction to ensure that the indicated segment is selected.
TYPE Returns the type (size in bytes) of the expression following the operator. The
type of an immediate value is 0.
PTR Typecast operator. The result is a memory reference with the value of the
expression following the operator and the type of the expression in front of
the operator.
SHL Logical shift left. Both expressions must be absolute immediate values, and
the result is an absolute immediate value.
SHR Logical shift right. Both expressions must be absolute immediate values, and
the result is an absolute immediate value.
NOT Bitwise negation. The expression must be an absolute immediate value, and
the result is an absolute immediate value.
AND Bitwise AND. Both expressions must be absolute immediate values, and the
result is an absolute immediate value.
OR Bitwise OR. Both expressions must be absolute immediate values, and the
result is an absolute immediate value.
XOR Bitwise exclusive OR. Both expressions must be absolute immediate values,
and the result is an absolute immediate value.
Compiler Optimizations
An example of the type of function you can write is as follows:
o The compiler only generates stack frames for nested routines, for routines
that have local parameters, or for routines that have parameters on the
stack.
o Locals is the size of the local variables and Params is the size of the
parameters. If both Locals and Params are zero, there is no entry code,
and the exit code consists simply of a RET instruction.
The automatically generated entry and exit code for the routine looks like this:
If locals include variants, long strings, or interfaces, they are initialized to zero but
not finalized.
32-bit
o Ordinal values are returned in AL (8-bit values), AX (16-bit values), or EAX
(32-bit values).
o Short strings and variants are returned in the temporary location pointed
to by @Result.
64-bit
o Values 8 bytes or less in size are return in RAX.
.PUSHNV Generates code to save and restore the non-volatile general purpose
<register> register in the prologue and epilogue.
.SAVENV <XMM
register> Same functionality as .PUSHNV for non-volatile XMM registers.
Generics Index
Presents an overview of generics, a terminology list, a summary of grammar
changes for generics, and details about declaring and using parameterized
types, specifying constraints on generics, and using overloads.
Topics
o Overview of Generics
o Declaring Generics
o Constraints in Generics
A method or data type that uses other types in its definition can be made more
general by substituting one or more particular types with type parameters. Then
you add those type parameters to a type parameter list in the method or data
structure declaration. This is similar to the way that you can make a procedure
more general by substituting instances of a literal constant in its body with a
parameter name and adding the parameter to the parameter list of the
procedure.
For example, a TMyList class that maintains a list of objects (of the TObject type)
can be made more reusable and type-safe by substituting uses of TObject with a
type parameter name (such as 'T'), and adding the type parameter to the class's
type parameter list so that it becomes TMyList<T>.
For example, the list might be used as TMyList<Double>. This creates a new type,
TMyList<Double>, whose definition is identical to TMyList<T> except that all
instances of 'T' in the definition are replaced with 'Double'.
Code Examples
For example, TSIPair is a class holding two data types, String and Integer:
To make a class independent of data type, replace the data type with a type
parameter:
type
TPair<TKey,TValue> = class // declares TPair type with two type parameters
private
FKey: TKey;
FValue: TValue;
public
function GetKey: TKey;
procedure SetKey(Key: TKey);
function GetValue: TValue;
procedure SetValue(Value: TValue);
property Key: TKey read GetKey write SetKey;
property Value: TValue read GetValue write SetValue;
end;
type
TSIPair = TPair<String,Integer>; // declares instantiated type
TSSPair = TPair<String,String>; // declares with other data types
TISPair = TPair<Integer,String>;
TIIPair = TPair<Integer,Integer>;
TSXPair = TPair<String,TXMLNode>;
Interface GUID
In Win32, an instantiated interface type does not have an interface GUID.
Instantiation timing
Generic types are instantiated at compile time and emitted into executables
and relocatable files. Instance variables of a generic type are instantiated at run
time for classes and at compile time for generic records. The RTTI for generic
classes is only generated when the classes are instantiated. RTTI for instantiated
classes follows just as for non-generic classes. If the generic class has a generic
method, then the instantiated generic class will not have RTTI for that generic
method.
Dynamic instantiation
Dynamic instantiation at run time is not supported.
Interface constraints
The Win32 interface is not a "light" interface. This means all type parameters with
interface constraints always support the COM IUnknown methods _AddRef,
_Release, and QueryInterface or inherit from TInterfacedObject. Record types
cannot specify an interface constraint parameter.
Type generic A type declaration that requires type parameters to be supplied in order to
form an actual type.
List<Item> is a type generic (or generic) in the following example:
type
List<Item> = class
...
end;
type
List<Item> = class
...
end;
Type argument A particular type used with a type identifier in order to make an instantiated
and type. Using the previous example, List<Integer> is the instantiated type
Type identifier (instantiated generic), List is the type identifier, and Integer is the type
argument.
Closed A constructed type having all its parameters resolved to actual types.
constructed List<Integer> is closed because Integer is an actual type.
type
Open A constructed type having at least one parameter that is a type parameter. If
constructed T is a type parameter of a containing class, List<T> is an open constructed
type type.
Instantiation The compiler generates real instruction code for methods defined in generics
and real virtual method table for a closed constructed type. This process is
required before emitting a Delphi compiled unit file (.dcu) or object file (.obj)
for Win32.
For example:
type
TPair<TKey,TValue> = class // TKey and TValue are type parameters
FKey: TKey;
FValue: TValue;
function GetValue: TValue;
end;
Note: You must call the default constructor and initialize the class
fields before calling the GetValue method.
Type Argument
Generic types are instantiated by providing type arguments. In Delphi, you can
use any type as a type argument except for the following: a static array, a short
string, or a record type that (recursively) contains a field of one or more of these
two types.
type
TFoo<T> = class
FData: T;
end;
var
F: TFoo<Integer>; // 'Integer' is the type argument of TFoo<T>
begin
...
end.
type
TFoo<T> = class
type
TBar = class
X: Integer;
// ...
end;
end;
// ...
TBaz = class
type
TQux<T> = class
X: Integer;
// ...
end;
// ...
end;
To access the TBar nested type, you must specify a construction of the TFoo type
first:
var
N: TFoo<Double>.TBar;
type
TFoo1<T> = class(TBar) // Actual type
end;
For example:
type
TRecord<T> = record
FData: T;
end;
type
IAncestor<T> = interface
function GetRecord: TRecord<T>;
end;
IFoo<T> = interface(IAncestor<T>)
procedure AMethod(Param: T);
end;
type
TFoo<T> = class(TObject, IFoo<T>)
FField: TRecord<T>;
procedure AMethod(Param: T);
function GetRecord: TRecord<T>;
end;
type
anArray<T>= array of T;
IntArray= anArray<integer>;
Procedural Types
The procedure type and the method pointer can be declared with type
parameters. Parameter types and result types can also use type parameters.
type
TMyProc<T> = procedure(Param: T);
TMyProc2<Y> = procedure(Param1, Param2: Y) of object;
type
TFoo = class
procedure Test;
procedure MyProc(X, Y: Integer);
end;
procedure TFoo.Test;
var
X: TMyProc<Integer>;
Y: TMyProc2<Integer>;
begin
X := Sample;
X(10);
Y := MyProc;
Y(20, 30);
end;
var
F: TFoo;
begin
F := TFoo.Create;
F.Test;
F.Free;
end.
Parameterized Methods
Methods can be declared with type parameters. Parameter types and result
types can use type parameters. However, constructors and destructors cannot
have type parameters, and neither can virtual, dynamic, or message methods.
Parameterized methods are similar to overloaded methods.
type
TFoo = class
procedure Test;
procedure CompareAndPrintResult<T>(X, Y: T);
end;
procedure TFoo.Test;
begin
CompareAndPrintResult<String>('Hello', 'World');
CompareAndPrintResult('Hello', 'Hello');
CompareAndPrintResult<Integer>(20, 20);
CompareAndPrintResult(10, 20);
end;
var
F: TFoo;
begin
F := TFoo.Create;
F.Test;
ReadLn;
F.Free;
end.
For example:
type
TFoo<T> = class
X: T;
end;
TBar<S> = class(TFoo<S>)
Y: T; // error! unknown identifier "T"
end;
var
F: TFoo<Integer>;
begin
F.T // error! unknown identifier "T"
end.
For example:
type
TFoo = class
procedure Proc<T>(A: T); overload;
procedure Proc(A: String); overload;
procedure Test;
end;
procedure TFoo.Test;
begin
Proc('Hello'); // calls Proc(A: String);
Proc<String>('Hello'); // calls Proc<T>(A: T);
end;
Type Compatibility
Two non-instantiated generics are considered assignment compatible only if
they are identical or are aliases to a common type.
You can specify both "constructor" and "class" for a constraint. However, "record"
cannot be combined with other reserved words. Multiple constraints act as an
additive union ("AND" logic).
The examples given here show only class types, although constraints apply to all
forms of generics.
Declaring Constraints
Constraints are declared in a fashion that resembles type declarations in regular
parameter lists:
type
TFoo<T: ISerializable> = class
FField: T;
end;
In the example declaration given here, the 'T' type parameter indicates that it
must support the ISerializable interface. In a type construction like
TFoo<TMyClass>, the compiler checks at compile time to ensure that TMyClass
actually implements ISerializable.
type
TFoo<T: ISerializable; V: IComparable>
type
TFoo<S, U: ISerializable> ...
In the example above, S and U are both bound to the ISerializable constraint.
Multiple Constraints
Multiple constraints can be applied to a single type parameters as a comma list
following the colon:
type
TFoo<T: ISerializable, ICloneable; V: IComparable> ...
Constrained type parameters can be mixed with "free" type parameters. For
example, all the following are valid:
type
TFoo<T; C: IComparable> ...
TBar<T, V> ...
TTest<S: ISerializable; V> ...
// T and V are free, but C and S are constrained
Types of Constraints
Interface Type Constraints
A type parameter constraint may contain zero, one, or a comma separated list
of multiple interface types.
A type parameter constrained by an interface type means that the compiler will
verify at compile time that a concrete type passed as an argument to a type
construction implements the specified interface type(s).
type
TFoo<T: ICloneable> ...
TError = class
end;
var
X: TFoo<TTest1>; // TTest1 is checked for ICloneable support here
// at compile time
Y: TFoo<TError>; // exp: syntax error here - TError does not support
// ICloneable
Compatibility of class types follows the normal rules of OOP type compatibilty -
descendent types can be passed where their ancestor types are required.
Constructor Constraints
A type parameter may be constrained by zero or one instance of the reserved
word "constructor". This means that the actual argument type must be a class
that defines a default constructor (a public parameterless constructor), so that
methods within the generic type may construct instances of the argument type
using the default constructor of the argument type, without knowing anything
about the argument type itself (no minimum base type requirements).
In a constraint declaration, you can mix "constructor" in any order with interface
or class type constraints.
Class Constraint
A type parameter may be constrained by zero or one instance of the reserved
word "class". This means that the actual type must be a class type.
Record Constraint
A type parameter may be constrained by zero or one instance of the reserved
word "record". This means that the actual type must be a value type (not a
reference type). A "record" constraint cannot be combined with a "class" or
"constructor" constraint.
For example:
type
TFoo<T: ISerializable, ICloneable> = class
FData: T;
procedure Test;
end;
procedure TFoo<T>.Test;
begin
FData.Clone;
end;
The compiler looks for "Clone" methods in ISerializable and ICloneable, since
FData is of type T, which is guaranteed to support both those interfaces. If both
interfaces implement "Clone" with the same parameter list, the compiler issues an
ambiguous method call error and require you to typecast to one or the other
interface to disambiguate the context.
procedure Test;
var
FI: TFoo<Integer>;
begin
FI := TFoo<Integer>.Create;
FI.Free;
end;
var
FI: TFoo<Integer>;
FS: TFoo<String>;
begin
FI := TFoo<Integer>.Create;
FI.Free;
FS := TFoo<String>.Create;
FS.Free;
Test;
Writeln(TFoo<Integer>.FCount); // outputs 2
Writeln(TFoo<String>.FCount); // outputs 1
end.
Introduction
Attributes are a language feature in Delphi that allows annotating types and
type members with special objects that carry additional information. This
information can be queried at run time. Attributes extend the normal Object-
Oriented model with Aspect-Oriented elements.
In general, attributes are useful when building general purpose frameworks that
analyze structured types such as objects or records at run time and introduce
new behavior based on additional information supplied by the annotated
attributes.
Topics
o Declaring Custom Attributes (RTTI)
Declaring an Attribute
An attribute is a simple class type. To declare your own custom attribute, you
must derive it from a special predefined class: System.TCustomAttribute:
type
MyCustomAttribute = class(TCustomAttribute)
end;
type
[MyCustomAttribute]
TSpecialInteger = type integer;
TSomeClass = class
[MyCustomAttribute]
procedure Work;
end;
Note that the declared attribute class must not be declared as class abstract
and should not contain any abstract methods. Even though the compiler allows
you to use these attributes for annotation, the built binary will not include them in
the emitted RTTI information.
o MyCustomAttribute
The class with the 'Attribute' suffix (MyCustomAttribute) is always used, and the
class with the shorter name (MyCustom) becomes inaccessible.
The following code snippet demonstrates this issue. One might expect the
TCustomAttribute subclass, Test, to be applied but because of implicit name
shortening, TestAttribute will actually be applied where either [Test] or
[TestAttribute] are used.
// Becomes unaccessible
Test = class(TCustomAttribute)
end;
Constructors in Attributes
Normally, an attribute is designed to carry some additional information that can
be queried at run time. To allow specifying custom information for the attribute
class, you must declare constructors for it:
type
AttributeWithConstructor = class(TCustomAttribute)
public
constructor Create(const ASomeText: String);
end;
type
[AttributeWithConstructor('Added text value!')]
TRecord = record
FField: Integer;
end;
The method resolution works for attributes as well, which means that you can
define overloaded constructors in the custom-defined attribute. Declare only
constructors that accept constant values and not out or var ones. This comes
out of a basic restriction in how attributes work and is discussed in more detail in
Annotating Types and Type Members.
General Syntax
To annotate a Delphi type or a member, such as a class or a class member, you
must precede the declaration of that type by the name of the attribute class
between brackets:
If the name of the attribute class ends in "Attribute", you can also omit the
"Attribute" suffix:
[Custom]
procedure DoSomething;
Having a set of parenthesis after the attribute class name is also a valid syntax:
[Custom()]
TMyRecord = record;
Some attributes accept parameters. To pass arguments to your attribute, use the
same syntax as you use for method calls:
[Custom(Argument1, Argument2, …)]
TSimpleType = set of (stOne, stTwo, stThree);
To annotate a single type with several attributes, you can either use several sets
of brackets:
[Custom1]
[Custom2(MyArgument)]
FString: String;
o You can only use constant expressions, including sets, strings, and ordinal
expressions.
o You can use TypeInfo() to pass type information because the RTTI block
addresses are known at compile time.
o You can use class references because the metaclass addresses are
known at compile time.
o You cannot use out or var parameters because they require run-time
evaluation of addresses of passed parameters.
The following code exemplifies the case in which the compiler does not compile
the annotation:
var
a, b: Integer;
type
[SomeAttribute(a + b)]
TSomeType = record
// …
end;
const
a = 10;
b = 20;
type
[SomeAttribute(a + b)]
TSomeType = record
// …
end;
The values of a and b are known at compile time; thus, the constant expression is
evaluated directly.
The actual instantiation of attributes happens when the consumer code queries
for them in a given type or type member. This means that instances of attribute
classes are not created automatically, but rather when the program explicitly
searches for them. There is no guaranteed order in which attributes are
instantiated, nor it is known how many instances are created. A program should
not depend on such consequences.
To extract the attribute from the TSomeType type, the user code must employ
the functionality exposed by the System.Rtti unit. The following example
demonstrates the extraction code:
As seen in the example above, the user must specifically write code to query for
attributes annotated to a type. The actual attribute instances are created in the
TRttiType.GetAttributes method. Note that the example does not destroy the
instances; the TRttiContext frees all resources afterward.
Exceptions
Because the actual instantiation of attributes is performed in the user code, one
must be aware of the possible exceptions that may occur in the attributes'
constructors. The general recommendation is to use a try .. except clause
surrounding the code that queries for attributes.
FValue := AValue;
end;
and the annotation for TSomeType is changed to pass an empty string to the
attribute constructor:
type
[TSpecialAttribute('')]
TSomeType = record
...
end;
In concept, this is somewhat similar to dynamic proxies from .NET and Java. It is
like being able to derive from a class at run time, override methods (but not add
new instance fields), and then change the run-time type of an instance to this
new derived class.
Compiler Attributes
Some special attributes trigger certain features of Delphi compilers.
Ref
The Ref attribute is used to qualify constant function parameters so that they are
passed by reference (not by value) to the function. For more information, see
Constant Parameters.
Volatile
The volatile attribute is used to mark fields that are subject to change by
different threads, so that code generation does not optimize copying the value
in a register or another temporary memory location.
You can use the volatile attribute to mark the following declarations:
o Parameters
You cannot use the volatile attribute to mark the following declarations:
o Type
o Expressions
type
TMyClass = class
private
[volatile] FMyVariable: TMyType;
end;
Weak
The weak attribute is used to mark a declaration as a weak reference. For more
information, see Weak References.
o The -JL switch generates .lib, .bpi, .bpl and .obj files from a .dpk file, and
header files for all units in the package.
DOs
Redeclaring All Inhereted Contructors
Unlike Delphi, C++ does not inherit constructors. For example, the following is
incorrect:
class A
{
public:
A(int x) {}
};
class B: public A
{
};
int main(void)
{
B *b = new B(5); // Error
delete b;
}
The header file generation logic of the Delphi compiler is aware of this language
difference and adds the missing inherited constructors to each derived class.
However, these constructors also initialize member variables of the class. This
causes problems if a base class invokes a virtual method that already initialized
one of these member variables to a non-default value. It is particularly important
to redeclare inherited constructors if the base constructor can initialize a
member of a delphireturn type in the class.
This example results in the following C++ code that arises compilation errors
associated with duplicated constructors:
MyPoint = class
public
constructor Polar(Radius, Angle: Single);
constructor Rect(X, Y: Single; Dummy: Integer = 0);
o Use the Named Constructor Idiom. This technique declares class static
factory members instead of named constructors when constructors are
overloaded with identical or similar parameters. This is particularly relevant
for the Delphi record type. The following example depicts a solution
based on this technique:
class MyPoint {
public:
static MyPoint Rect(float X, float Y); // Rectangular coordinates
static MyPoint Polar(float Radius, float Angle); // Polar coordinates
private:
MyPoint(float X, float Y); // Rectangular coordinates
float X_, Y_;
};
TTest = class
function GetPropI(Index: Integer): Longint; overload;
procedure SetProp(Index: Integer; Value: Longint); overload;
function GetPropS(Index: Integer): String; overload;
procedure SetProp(Index: Integer; Value: String); overload;
public
property Props[Index: Integer] : Longint read GetPropI write SetProp;
property Props[Index: Integer] : String read GetPropS write SetProp; default;
end;
However, the resulting interface in the header file does not work in C++, since
each property of a class must be unique.
type
GoodArray = TArray<Integer>;
BadArray<T> = array of T;
GoodArray is a concrete type that C++ can use. In contrast, BadArray contains a
dependent type, thus C++ cannot use it.
type
TPointD = record
X: Double;
Y: Double;
public
constructor Create(const X, Y: Double);
end;
TRectD = record
case Integer of
0:
(Left, Top, Right, Bottom: Double);
1:
(TopLeft, BottomRight: TPointD);
end;
};
#pragma pack(pop)
};
Note that this issue only affects previous-generation C++ compilers (BCC32 and
BCCOSX), it does not affect Clang-enhanced C++ compilers.
ShareAlike — If you remix, transform, or build upon the material, you must distribute your
contributions under the same license as the original.
No additional restrictions — You may not apply legal terms or technological measures that
legally restrict others from doing anything the license permits.
Notices:
You do not have to comply with the license for elements of the material in the public
domain or where your use is permitted by an applicable exception or limitation.
No warranties are given. The license may not give you all of the permissions necessary for
your intended use. For example, other rights such as publicity, privacy, or moral rights may
limit how you use the material.
Creative Commons Legal Code
Attribution-ShareAlike 4.0 International
Creative Commons public licenses provide a standard set of terms and conditions that creators and other
rights holders may use to share original works of authorship and other material subject to copyright and
certain other rights specified in the public license below. The following considerations are for informational
purposes only, are not exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the
public permission to use material in ways otherwise restricted by copyright and certain other rights. Our
licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they
choose before applying it. Licensors should also secure all rights necessary before applying our licenses so
that the public can reuse the material as expected. Licensors should clearly mark any material not subject to
the license. This includes other CC-licensed material, or material used under an exception or limitation to
copyright.
Considerations for the public: By using one of our public licenses, a licensor grants the public permission
to use the licensed material under specified terms and conditions. If the licensor’s permission is not
necessary for any reason–for example, because of any applicable exception or limitation to copyright–then
that use is not regulated by the license. Our licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other
reasons, including because others have copyright or other rights in the material. A licensor may make
special requests, such as asking that all changes be marked or described. Although not required by our
licenses, you are encouraged to respect those requests where reasonable.
Creative Commons Attribution-ShareAlike 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and
conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed
Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such
rights in consideration of benefits the Licensor receives from making the Licensed Material available under
these terms and conditions.
Section 1 – Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based
upon the Licensed Material and in which the Licensed Material is translated, altered, arranged,
transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar
Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a
musical work, performance, or sound recording, Adapted Material is always produced where the
Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your
contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses,
approved by Creative Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright
including, without limitation, performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License,
the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. Effective Technological Measures means those measures that, in the absence of proper authority,
may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty
adopted on December 20, 1996, and/or similar international agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to
Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name of a Creative Commons Public
License. The License Elements of this Public License are Attribution and ShareAlike.
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor
applied this Public License.
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public
License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed
Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
k. Share means to provide material to the public by any means or process that requires permission under
the Licensed Rights, such as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material available to the public including in
ways that members of the public may access the material from a place and at a time individually chosen
by them.
l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as
amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a
corresponding meaning.
Section 2 – Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a
worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the
Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to
Your use, this Public License does not apply, and You do not need to comply with its terms and
conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the
Licensed Rights in all media and formats whether now known or hereafter created, and to make
technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right
or authority to forbid You from making technical modifications necessary to exercise the Licensed
Rights, including technical modifications necessary to circumvent Effective Technological Measures.
For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4)
never produces Adapted Material.
5. Downstream recipients.
A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material
automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms
and conditions of this Public License.
B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from
You automatically receives an offer from the Licensor to exercise the Licensed Rights in the
Adapted Material under the conditions of the Adapter’s License You apply.
C. No downstream restrictions. You may not offer or impose any additional or different terms or
conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so
restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are
publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor
waives and/or agrees not to assert any such rights held by the Licensor to the limited extent
necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of
the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable
statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any
right to collect such royalties.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive
attribution, in any reasonable manner requested by the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous
modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the
URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium,
means, and context in which You Share the Licensed Material. For example, it may be reasonable to
satisfy the conditions by providing a URI or hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A)
to the extent reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following
conditions also apply.
1. The Adapter’s License You apply must be a Creative Commons license with the same License
Elements, this version or later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may
satisfy this condition in any reasonable manner based on the medium, means, and context in which
You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective
Technological Measures to, Adapted Material that restrict exercise of the rights granted under the
Adapter's License You apply.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed
Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share
all or a substantial portion of the contents of the database;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui
Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its
individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the
contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this
Public License where the Licensed Rights include other Copyright and Similar Rights.
Section 5 – Disclaimer of Warranties and Limitation of Liability.
a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor
offers the Licensed Material as-is and as-available, and makes no representations or warranties
of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This
includes, without limitation, warranties of title, merchantability, fitness for a particular purpose,
non-infringement, absence of latent or other defects, accuracy, or the presence or absence of
errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in
full or in part, this disclaimer may not apply to You.
b. To the extent possible, in no event will the Licensor be liable to You on any legal theory
(including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental,
consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of
this Public License or use of the Licensed Material, even if the Licensor has been advised of the
possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not
allowed in full or in part, this limitation may not apply to You.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner
that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if
You fail to comply with this Public License, then Your rights under this Public License terminate
automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your
discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek
remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or
conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this
Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You
unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein
are separate from and independent of the terms and conditions of this Public License.
Section 8 – Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit,
restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without
permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be
automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot
be reformed, it shall be severed from this Public License without affecting the enforceability of the
remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless
expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any
privileges and immunities that apply to the Licensor or You, including from the legal processes of any
jurisdiction or authority.
Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to
apply one of its public licenses to material it publishes and in those instances will be considered the
“Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the
CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a
Creative Commons public license or as otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative
Commons” or any other trademark or logo of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications to any of its public licenses or any other
arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of
doubt, this paragraph does not form part of the public licenses.
Additional languages available: Bahasa Indonesia, Español, euskara, Deutsch, Español, français, hrvatski,
italiano, latviski, Lietuvių, Nederlands, norsk, polski, português, suomeksi, svenska, te reo Māori, Türkçe,
čeština, Ελληνικά, русский, українська, اﻟﻌرﺑﯾﺔ, 日本語, 한국어. Please read the FAQ for more information
about official translations.