I learned about Delphi and my notes-types, variables and constants (Lecture 2)

Source: Internet
Author: User

1. Variables

The Pascal variable must be declared before use, and a data type must be specified when the variable is declared. The following is an example of variable declaration:

VarValue: Integer; IsCorrect: Boolean; A, B: Char; the declarative variable uses var as the keyword, in the format of var variable name: type;
2. Constants
Pascal allows constant declaration of a value that remains unchanged during the running of the program. Declaring a constant does not require a specific data type, but an initial value must be assigned. The compiler automatically selects the appropriate data type based on the assigned initial values. For example:Const
Thousand = 1000;
Pi = 3.14;
AuthorName ='Marco Cant authorization'; Constants and values cannot be changed during editing and running;
Delphi determines the Data Type of a constant based on its value. In the preceding example, the Thousand variable. Delphi selects the SmallInt data type (short integer -- the smallest integer type that can hold the Thousand variable ). If you want to tell Delphi to adopt a specific type, you can add the type name to the Declaration as follows:
const  Thousand: Integer = 1000;
For a famous constant, the compiler has two compilation options: the first is to allocate memory for the constant and put the value of the constant into the memory; the second is to copy the constant value every time the constant is used. The second method is suitable for simple constants.
3. Resource string constants
When defining a String constant, you can write as follows:
const  AuthorName = 'Marco Cantù';
From Delphi 3, you can write in another way:
resourcestring  AuthorName = 'Marco Cantù';
The preceding two statements define a constant, that is, a value that remains unchanged during the running of the program, but the implementation process of the two statements is different.ResourcestringThe string variables defined by the command are saved in the string table of the program resource. In the example ResStr, you can understand the actual function of the resource string. In the example, a button is set and the corresponding code is as follows:
resourcestring  AuthorName = 'Marco Cantù';  BookName = 'Essential Pascal';procedure TForm1.Button1Click(Sender: TObject);begin  ShowMessage (BookName + #13 + AuthorName);end;

The two strings in the above Code will be output in two lines, because the string is indicated by a branch character#13.

Interestingly, when you open the execution file in the resource editor, you will see your defined string in the program resource. This means that the string does not enter the compilation code, but is saved in a separate area of the execution file (EXE file.

Note:: Simply put, the advantages of using resources allow Windows to complete effective memory processing, and implement program localization without changing the source code (Translating strings into different languages ).

4. Data Types

Pascal has a variety of predefined data types, which can be divided into three categories: ordered data type, real number type and string type. Next we will first discuss the ordered type and the real number type. The string type will be discussed later. This section also describes the types defined in the Delphi library (not the predefined types of the compiler). These types can also be considered as predefined types.

Delphi also includesNo typeVariable data type, calledVariantIn the tenth lecture of this book, we will discuss this type. Variant is a data type that does not require type detection. It is introduced in Delphi 2 to process OLE Automation ).

5. Ordered type

An ordered type is a data type based on the concept "sequence" or "sequence. You can not only compare the sizes of two ordered values, but also obtain the precursor and successor of a given ordered value, or calculate their maximum or minimum values.

The three most important predefined order types are Integer, Boolean, and character (Integer, Boolean, Char ). Different types can be further subdivided based on their internal representation and value range. Table 3.1 lists the ordered Data Types of numbers.

Table 3.1: ordered data type of numbers

Size Signed value range Unsigned value range
8 bits ShortInt
-From 128 to 127
Byte
0 to 255
16 bits SmallInt
-From 32768 to 32767
Word
0 to 65,535
32 bits LongInt
-From 2,147,483,648 to 2,147,483,647
LongWord (from Delphi 4)
0 to 4,294,967,295
64 bits Int64  
16/32 bits Integer Cardinal

From the table, we can see that different data types correspond to different data representations, depending on the number and symbol bit of the data value. A value of the symbolic type can be positive or negative, but the value range is small, because the symbolic bit occupies a digit. The next section describes the actual Range of values for each type in the sample Range.

The last group of types in the table indicates 16/32, which indicates that the numerical expression method is different in 16-bit and 32-bit Delphi. The Integer and Cardinal types in this group are usually used, because they correspond to the digital representation inside the CPU.

Integer type in Delphi 4

In Delphi 3, the 32-bit unsigned value of the Cardinal type actually occupies 31 places and the maximum value is 2 billion. Delphi 4 adds an unsigned numeric type-LongWord, which is a real 32-bit value with a maximum value of 4 billion. Now the Cardinal type has become an alias of the LongWord type, except that LongWord can accommodate an unsigned number greater than 2 billion, and its numerical representation is consistent with that in the CPU.

Another new data type added in Delphi 4 isInt64Type, which can represent integers up to 18 digits. The ordered type routines (such as High and Low), numeric routines (such as Inc and Dec), and String Conversion routines (such as IntToStr) in the system support this new type. In turn, there are two new dedicated functionsStrToInt64AndStrToInt64DefConverts a string to a number.

Boolean Type

A boolean value is rarely used, unlike a Boolean value. The boolean values of ByteBool, WordBool, and LongBool are special. They are only used in Windows API functions.

In Delphi 3, to be compatible with Visual Basic and OLE AutomationByteBool,WordBoolAndLongBoolThe Boolean valueTRUESet the value to 1,FALSEThe value is still 0;BooleanType boolean values remain unchanged (TRUE1,FALSE0 ). If Boolean explicit type conversion is used in Delphi 2 code, errors may occur in future Delphi.

Character Type

There are two different types of characters ::ANSICharAndWideChar. The first type represents eight characters, corresponding to the ANSI character set that Windows has always followed; the second type represents 16 characters, corresponds to the double-byte characters (Unicode) supported by Windows NT, Windows 95, and 98. In Delphi 3, Char is the same as ANSIChar. Remember, the first 256 Unicode characters are exactly the same as the ANSI characters in any environment.

Constant characters can be represented by symbols, such'K', Which can also be represented by a number, such#78. The latter is still availableChrFunction is representedChr (78), UseOrdFunction can be converted in the opposite way.Ord (k).

Generally, it is better to represent letters, numbers, or symbols with symbols representing them, but it is better to use digits when special characters are involved. Common special characters are listed below:

  • #9Hop (Tab key)
  • #10Line feed
  • #13Enter)

Ordered type system routine

The Pascal Language and the Delphi System unit define a series of sequential operation routines, as shown in Table 3.2. C ++ programmers will notice the Inc routine, which can correspond to the ++ and ++ = operators (same for Dec routines ).

Table 3.2: ordered type system routine

Routine Function
Dec Decrease the value of a parameter in a routine by 1 or a specific value. The specific value can be defined in the second optional parameter.
Inc Increase the parameter value in the routine by 1 or a specific value.
Odd Returns true if the parameter is an odd number.
Pred Returns the forward value of the parameter value based on the sequence of the parameter in its data type definition.
Succ Returns the successor value of the parameter value.
Ord Sequence Number of the returned parameter value in its data type value set
Low Minimum value of the ordered data type corresponding to the return Parameter
High Maximum Value of the ordered data type corresponding to the return Parameter

Note that when some routines are used for constants, the compiler will automatically replace the routines with calculated values. For example, if you callHigh (X)If X is set to an integer, the compiler replaces this expression with the largest possible value in the integer type.

Real Number Type

The real number type represents floating point numbers of different formats.Single typeThe minimum number of bytes, which is 4 bytes, followedDoubleFloating point type, which occupies 8 bytes;ExtendedFloating point type, which occupies 10 bytes. These floating point data types with different precision are consistent with the IEEE (Association of Electrical and Electronics Engineers) standard floating point representation, and the CPU digital coprocessor directly supports these types, the fastest processing speed.

RealThe definitions of types in Delphi 2 and Delphi 3 are the same as those in the 16-bit version and both occupy 6 bytes. Borland does not advocate this type, but it is recommended to replace the Single, Double, and Extended types. This is becauseRealThe 6-byte old format is neither supported by Intel CPU nor listed in the official IEEE real-time format. To completely solve this problem, Delphi 4 had to modifyRealThe type definition is changed to the Standard 8-byte floating point type, which causes compatibility problems. However, if necessary, you can use the following compilation instructions to overcome compatibility problems and restoreRealType Definition:

{$REALCOMPATIBILITY ON}

There are also two strange data types:CompType andCurrencyType,CompType: 8 bytes to describe a very large integer (this type can support digits with 18 decimal places );CurrencyType (16-bit versions of Delphi do not support this type) indicates a value with four decimal places. Its decimal point length is fixed, and it also occupies 8 bytes like the Comp type. As shown in the name, the Currency data type is added to operate precise four decimal Currency values.

For real-type data, we cannot compile a program similar to Range, because the High, Low, and Ord functions cannot be used for real-type values. Theoretically, the real type represents an infinite number set; the ordered type represents a finite number set.

Note:: Let me explain the problem further. For integer 23, you can determine what the number is after '23'. because the number of integers is limited, they have a definite value range and order. Floating Point Numbers are infinite and unordered in a very small value range. In fact, what is the value between 23 and 24? Which value is the value after 23.46? 23.47, 23.461, or 23.4601? It is hard to say clearly.

Date and Time

Delphi also uses real numbers to represent date and time data. But for the sake of accuracy, Delphi has definedTDateTimeData type. This is a floating point type because it must be wide enough to make the variable contain years, months, days, hours, minutes, And seconds, or even milliseconds. The date value is counted by day. It starts from 1899-12-30 and is placed in the integer part of the TDateTime type. The time value is placed in the decimal part.

TDateTime is not a predefined type that can be directly recognized by the compiler. It is defined in the System Unit:

Type
TDateTime =TypeDouble;

It is easy to use the TDateTime type Because Delphi defines a series of operation functions for this type. Table 3.3 lists these functions.

Table 3.3: TDateTime type system routine

Routine Function
Now Returns the current date and time.
Date Returns the current date.
Time Returns the current time.
DateTimeToStr Convert the date and time values into strings by default format. For specific format conversion, the FormatDateTime function is available.
DateTimeToString Copy the date and time values to the string buffer in the default format
DateToStr Convert the date part of the TDateTime value into a string
TimeToStr Convert the time part of the TDateTime value into a string
FormatDateTime Convert the date and time values into strings in a specific format
StrToDateTime Converts a string with date and time information to a TdateTime value. If the string is incorrect, an exception is thrown.
StrToDate Convert a string with date information to the TDateTime format
StrToTime Convert a string with time information to the TDateTime format
DayOfWeek Calculate the number of days in a week based on the passed date parameter.
DecodeDate Returns the year, month, and day values based on the date value.
DecodeTime Returns the time, minute, second, and millisecond values based on the time value.
EncodeDate The combined year, month, and day values are of the TDateTime type.
EncodeTime The combined time, minute, second, and millisecond values are of the TDateTime type.

So far, we have seen that all predefined data types are defined by Pascal. Delphi also contains the data types defined by the Windows system. These data types are not part of the Pascal language, but part of the Windows library. Windows types include new default types (such as DWORD or UINT), various record (or structure) types, and pointer types.

In Windows, handle is the most important data type, which will be discussed in the ninth lecture.

Type ing and conversion

As you know, you cannot assign a variable to another variable of different types. If you need to do so, there are two ways to choose from. The first method is to use Typecasting, which uses a function symbol with the target data type name:

var  N: Integer;  C: Char;  B: Boolean;begin  N := Integer ('X');  C := Char (N);  B := Boolean (0);

You can map data types with the same bytes length. It is usually safe to map data types between ordered data types or between real data types. You can also map data types between pointer types and objects as long as you understand what you are doing.

However, in general, type ing is a more dangerous programming technology, because it allows you to access a seemingly non-value, which is like a substitute for other values. Because the internal representations of data types do not usually match each other, it is difficult to track errors. Therefore, you should avoid using type ing whenever possible.

The second method is to use a type conversion routine. Table 3.4 summarizes various types of conversion routines. The data types involved in some routines will be discussed in the next section. Note that the table does not include conversion routines for special types (such as TDateTime and variant), nor include special routines for formatting, suchFormatAndFormatFloatRoutine.

Table 3.4: type conversion system routine

Routine Function
Chr Converts an ordered data to an ANSI character.
Ord Converts an ordered type value to its serial number.
Round Converts an integer value to a rounding value.
Trunc Convert a real-type value to the integer value after decimal Truncation
Int Returns the integer portion of a floating point.
IntToStr Converts a value to a string.
IntToHex Converts a value to a hexadecimal string.
StrToInt Converts a string to an integer. If the string is not a valid integer, an exception is thrown.
StrToIntDef Converts a string to an integer. If the string is invalid, a default value is returned.
Val Convert a string to a number (the traditional Turbo Pascal routine is used for backward compatibility)
Str Convert numbers to formatted strings (traditional Turbo Pascal routines are used for backward compatibility)
StrPas Converts a null-terminated string to a Pascal-type string. In 32-bit Delphi, this type conversion is automatically performed.
StrPCopy Copy a Pascal string to a zero-terminated string. In 32-bit Delphi, this type conversion is automatically performed.
StrPLCopy Copy part of a Pascal string to a zero-terminated string.
FloatToDecimal Converts a floating point number to a decimal floating point record type that contains an index, number, and symbol.
FloatToStr Converts a floating point value to a string in the default format.
FloatToStrF Converts a floating point value to a string of a specific format.
FloatToText Copy a floating point value to a string buffer in a specific format
FloatToTextFmt Same as the preceding example, a floating point value is copied to a string buffer in a specific format.
StrToFloat Converts a Pascal string to a floating point number.
TextToFloat Converts a zero-end string to a floating-point number.

Note:: In the latest version of the Delphi Pascal Compiler, the Round function is based on the cpu fpu (Floating Point Component) processor. This kind of processor uses the so-called "banker rounding method", that is, when the middle value (such as 5.5, 6.5) implements the Round function, the processor determines whether to perform rounding Based on the odd or even number before the decimal point. For example, the result of 5.5 Round is 6, and the result of 6.5 Round is 6 because 6 is an even number. Specific Windows types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.