Saturday, February 26, 2011

Simple Delphi data types

Simple Delphi data types
Like many modern languages, Delphi provides a rich variety of ways of storing data. We'll cover the basic, simple types here. Before we do, we'll show how to define a variable to Delphi:

var // This starts a section of variables
LineTotal : Integer; // This defines an Integer variable called LineTotal
First,Second : String; // This defines two variables to hold strings of text

We'll show later exactly where this var section fits into your program. Notice that the variable definitions are indented - this makes the code easier to read - indicating that they are part of the var block.

Each variable starts with the name you choose, followed by a : and then the variable type. As with all Delphi statements, a ; terminates the line. As you can see, you can define multiple variables in one line if they are of the same type.

It is very important that the name you choose for each variable is unique, otherwise Delphi will not know how to identify which you are referring to. It must also be different from the Delphi language keywords. You'll know when you have got it right when Delphi compiles your code OK (by hitting Ctrl-F9 to compile).

Delphui is not sensitive about the case (lower or upper) of your names. It treats theCAT name the same as TheCat.

Number types
Delphi provides many different data types for storing numbers. Your choice depends on the data you want to handle. Our Word Processor line count is an unsigned Integer, so we might choose Word which can hold values up to 65,535. Financial or mathematical calculations may require numbers with decimal places - floating point numbers.

var
// Integer data types :
Int1 : Byte; // 0 to 255
Int2 : ShortInt; // -127 to 127
Int3 : Word; // 0 to 65,535
Int4 : SmallInt; // -32,768 to 32,767
Int5 : LongWord; // 0 to 4,294,967,295
Int6 : Cardinal; // 0 to 4,294,967,295
Int7 : LongInt; // -2,147,483,648 to 2,147,483,647
Int8 : Integer; // -2,147,483,648 to 2,147,483,647
Int9 : Int64; // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

// Decimal data types :
Dec1 : Single; // 7 significant digits, exponent -38 to +38
Dec2 : Currency; // 50+ significant digits, fixed 4 decimal places
Dec3 : Double; // 15 significant digits, exponent -308 to +308
Dec4 : Extended; // 19 significant digits, exponent -4932 to +4932

Some simple numerical variable useage examples are given below - fuller details on numbers is given in the Numbers tutorial.

Text types
Like many other languages, Delphi allows you to store letters, words, and sentences in single variables. These can be used to display, to hold user details and so on. A letter is stored in a single character variable type, such as Char, and words and sentences stored in string types, such as String.

var
Str1 : Char; // Holds a single character, small alphabet
Str2 : WideChar; // Holds a single character, International alphabet
Str3 : AnsiChar; // Holds a single character, small alphabet
Str4 : ShortString; // Holds a string of up to 255 Char's
Str5 : String; // Holds strings of Char's of any size desired
Str6 : AnsiString; // Holds strings of AnsiChar's any size desired
Str7 : WideString; // Holds strings of WideChar's of any size desired

Some simple text variable useage examples are given below - fuller details on strngs and characters is given in the Text tutorial.

Logical data types
These are used in conjunction with programming logic. They are very simple:

var
Log1 : Boolean; // Can be 'True' or 'False'

Boolean variables are a form of enumerated type. This means that they can hold one of a fixed number of values, designated by name. Here, the values can be True or False. See the tutorials on Logic and Looping for further details.

Sets, enumerations and subtypes
Delphi excels in this area. Using sets and enumerations makes your code both easier to use and more reliable. They are used when categories of data are used. For example, you may have an enumeration of playing card suits. You literally enumerate the suit names. Before we can have an enumerated variable, we must define the enumeration values. This is done in a type section.

type
TSuit = (Hearts, Diamonds, Clubs, Spades); // Defines the enumeration
var
suit : TSuit; // An enumeration variable

Sets are often confused with enumerations. The difference is tricky to understand. An enumeration variable can have only one of the enumerated values. A set can have none, 1, some, or all of the set values. Here, the set values are not named - they are simply indexed slots in a numeric range. Confused? Well, here is an example to try to help you out. It will introduce a bit of code a bit early, but it is important to understand.

type
TWeek = Set of 1..7; // Set comprising the days of the week, by number
var
week : TWeek;
begin
week := [1,2,3,4,5]; // Switch on the first 5 days of the week
end;

See the Set reference, and the Sets and enumerations tutorial for further details. That tutorial introduces a further data type - a subrange type.


Using these simple data types
Variables can be read from and written to. This is called assignment. They can also be used in expressions and programming logic. See the Text tutorial and Programming logic tutorial for more about these topics.

Assigning to and from variables
Variables can be assigned from constant values, such as 23 and 'My Name', and also from other variables. The code below illustrates this assignment, and also introduces a further section of a Delphi program : the const (constants) section. This allows the programmer to give names to constant values. This is useful where the same constant is used throughout a program - a change where the constant is defined can have a global effect on the program.

Note that we use upper case letters to identify constants. This is just a convention, since Delphi is not case sensitive with names (it is with strings). Note also that we use = to define a constant value.

types
TWeek = 1..7; // Set comprising the days of the week, by number
TSuit = (Hearts, Diamonds, Clubs, Spades); // Defines an enumeration

const
FRED = 'Fred'; // String constant
YOUNG_AGE = 23; // Integer constant
TALL : Single = 196.9; // Decimal constant
NO = False; // Boolean constant

var
FirstName, SecondName : String; // String variables
Age : Byte; // Integer variable
Height : Single; // Decimal variable
IsTall : Boolean; // Boolean variable
OtherName : String; // String variable
Week : TWeek; // A set variable
Suit : TSuit; // An enumeration variable

begin // Begin starts a block of code statements
FirstName := FRED; // Assign from predefined constant
SecondName := 'Bloggs'; // Assign from a literal constant
Age := YOUNG_AGE; // Assign from predefined constant
Age := 55; // Assign from constant - overrides YOUNG_AGE
Height := TALL - 5.5; // Assign from a mix of constants
IsTall := NO; // Assign from predefined constant
OtherName := FirstName; // Assign from another variable
Week := [1,2,3,4,5]; // Switch on the first 5 days of the week
Suit := Diamonds; // Assign to an enumerated variable
end; // End finishes a block of code statements

FirstName is now set to 'Fred'
SecondName is now set to 'Bloggs'
Age is now set to 55
Height is now set to 191.4
IsTall is now set to False
OtherName is now set to 'Fred'
Week is now set to 1,2,3,4,5
Suit is now set to Diamonds (Notice no quotes)

Note that the third constant, TALL, is defined as a Single type. This is called a typed constant. It allows you to force Delphi to use a type for the constant that suits your need. Ohterwise, it will make the decision itself.


Compound data types
The simple data types are like single elements. Delphi provides compound data types, comprising collections of simple data types.

These allow programmers to group together variables, and treat this group as a single variable. When we discuss programming logic, you will see how useful this can be.

Arrays
Array collections are accessed by index. An array holds data in indexed 'slots'. Each slot holds one variable of data. You can visualise them as lists. For example:

var
Suits : array[1..4] of String; // A list of 4 playing card suit names

begin
Suits[1] := 'Hearts'; // Assigning to array index 1
Suits[2] := 'Diamonds'; // Assigning to array index 2
Suits[3] := 'Clubs'; // Assigning to array index 3
Suits[4] := 'Spades'; // Assigning to array index 4
end;

The array defined above has indexes 1 to 4 (1..4). The two dots indicate a range. We have told Delphi that the array elements will be string variables. We could equally have defined integers or decimals.

For more on arrays, see the Arrays tutorial.

Records
Records are like arrays in that they hold collections of data. However, records can hold a mixture of data types. Ther are a very powerful and useful feature of Delphi, and one that distinguishes Delphi from many other languages.

Normally, you will define your own record structure. This definition is not itself a variable. It is called a data type (see Types for further on this). It is defined in a type data section. By convention, the record type starts with a T to indicate that it is a type not real data (types are like templates). Let us define a customer record:

type
TCustomer Record
firstName : string[20];
lastName : string[20];
age : byte;
end;

Note that the strings are suffixed with [20]. This tells Delphi to make a fixed space for them. Since strings can be a variable length, we must tell Delphi so that it can make a record of known size. Records of one type always take up the same memory space.

Let us create a record variable from this record type and assign to it:

var
customer : TCustomer; // Our customer variable
begin
customer.firstName := 'Fred'; // Assigning to the customer record
customer.lastName := 'Bloggs';
customer.age := 55;
end;

customer.firstName is now set to 'Fred'
customer.lastName is now set to 'Bloggs'
customer.age is now set to 55

Notice how we do not use an index to refer to the record elements. Records are very friendly - we use the record element by its name, separated from the record name by a qualifying dot. See the Records tutorial for further on records.

Objects
Objects are collections of both data and logic. They are like programs, but also like data structures. They are the key part of the Object oriented nature of Delphi. See the Object orientation tutorial for more on this advanced topic.


Other data types
The remaining main object types in Delphi are a mixed bunch:

Files
File variables represent computer disk files. You can read from and write to these files using file access routines. This is a complex topic covered in Files.

Pointers
Pointers are also the subject of an advanced topic - see Pointer reference. They allow variables to be indirectly referenced.

Variants
Variants are also an advanced topic - see Variant. They allow the normal Delphi rigid type handling to be avoided. Use with care!

No comments:

Post a Comment