Pascal type, variables, and constants

Source: Internet
Author: User

The original PASCAL Language was built on some simple concepts that are now widely used inProgramming Language. The most important concept is the data type. The data type determines the valid values of the variable and the operations that can be performed on these values. The concept of Pascal data type is stronger than that of C language and basic language in the early days. In C language, arithmetic data types can be exchanged. In the early BASIC language, there was no concept similar to that of data type.

Variable

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;

KeywordsVaRIt can be used in many places, for example, in the beginning of a function or process, to declare a local variable of a function or process, or in a unit to declare a full variable.VaRThe keyword is followed by a list of variable names. Each variable name is followed by a colon and data type name. Multiple variables can be declared in one row, the last sentence in the preceding example.

Once the variable type is specified, you can only perform operations supported by the variable type. For example, you can use a Boolean value in a judgment operation and an integer value in a numeric expression. You cannot mix a Boolean value with an integer value (in C ).

Use a simple value assignment statement to write the followingCode:

Value: = 10; iscorrect: = true;

However, the following statement is incorrect because the data types of the two variables are different:

 
Value: = iscorrect;// Error

Compile this code in Delphi with the following error message:Incompatible types: 'integer 'and 'boolean'. (incompatible types: 'integer' and 'boolean '). Errors like this are usually programming errors, becauseTrueOrFalseIt makes no sense to assign the value to an integer variable. You shouldn't blame Delphi for prompting such an error message. If there is something wrong in the code, Delphi should certainly give a warning.

It is often difficult to convert the value of a variable from one type to another. In some cases, type conversion is automatically implemented. However, special system functions must be called, convert data types by changing the internal representation of data.

In Delphi, When you declare a full variable, you can assign it an initial value. For example, you can write:

 
VaRValue: integer = 10; correct: Boolean = true;

This initialization method can only be used for full-process variables, but not for variables of processes or methods.

Constant

ForProgramThe value remains unchanged during running. Pascal allows constant declaration. 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:

 
ConstThousand = 1000; Pi = 3.14; authorname ='Marco cant authorization';

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:

 
ConstThousand: 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.

Note:: The 16-bit delphi allows you to change the defined constant value while the program is running, just like a variable. 32-bit delphi allows this operation for backward compatibility, as long as you attach$ JCompile the command, or select the project option dialog box.CompilerOn the (compiler) pageAssignable typed ConstantsCheck box. However, I strongly recommend that you do not use the above operations here, because assigning new values to constants will prevent the compiler from optimizing constants, instead, declare a variable directly.

Resource String constant

When defining a String constant, you can write as follows:

 
ConstAuthorname ='Marco cant authorization';

From Delphi 3, you can write in another way:

 
ResourcestringAuthorname ='Marco cant authorization';

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:

 
ResourcestringAuthorname ='Marco cant authorization'; Bookname ='Essential Pascal';ProcedureTform1.button1click (Sender: tobject );BeginShowmessage (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:: In short, the advantages of using resources allow windows to complete effective memory processing, and there is no need to change it.Source codeProgram localization (Translating strings into different languages ).

Data Type

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, calledVariantThis type will be discussed in chapter 10 of this book. Variant is a data type that does not require type detection. It is introduced in Delphi 2 to process OLE automation ).

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)

Example: Range

To enable you to understand different values of ordered types, I wrote a Delphi program example named range. The result is shown in Figure 3.1.

Figure 3.1 simple example range shows ordered data type information (an integer is used in this example)

The range program is based on a simple form with six buttons (named according to the ordered data type) and several labels for displaying information, as shown in Figure 3.1. The label column on the far left of the form displays static text, and the label column on the left displays the data type information each time you click the button.

Every time you press a button on the right of the form, the program will update the display content of the label in the second column. The displayed content includes the data type, number of bytes, maximum and minimum values that can be stored for this type. Each button has its own onclick event because its computing code is slightly different. For example, the source code of the onclick event of the integer button (btninteger) is as follows:

 
ProcedureTformrange. btnintegerclick (Sender: tobject );BeginLabeltype. Caption: ='Integer'; Labelsize. Caption: = inttostr (sizeof (integer); labelmax. Caption: = inttostr (high (integer); labelmin. Caption: = inttostr (low (integer ));End;

If you have Delphi programming experience, you can check the source code of the program to understand how the program works. For beginners, pay attentionSizeof, high, lowYou can use these three functions. The high and low functions return the same order type as the parameter (here it is an integer), and the sizeof function returns the integer data. The Return Value of the function is converted into a string using the inttostr function, and then assigned the caption attribute of the three tags.

Other button events are similar to the preceding ones. The only difference is that the parameter types passed to functions are different. Figure 3.2 shows the execution result of the 16-bit delphi Compilation Program under Windows 95. Comparison between figure 3.1 and Figure 3.2 shows the difference between a 16-bit integer and a 32-bit integer.

Figure 3.2: integer information displayed in the result of range running in 16-bit delphi

The size of integer bytes depends on the CPU and operating system you are using. In 16-bit windows, integer variables take up two bytes. In 32-bit windows, integer variables take up four bytes. Therefore, the range program compiled in the two environments will get different results.

If your program has no special requirements on the size of integers,IntegerThe differences between types in different versions are not a big problem. If you save an integer In one version, you may encounter some problems when taking this integer out in another version. In this case, you should adopt platform-independent data types suchLongintOrSmallint. In mathematical computing or non-special code, your best choice is to stick to the standard integer corresponding to the platform, that is, to use the CPU's favorite Integer type. When processing integers,IntegerIt should be your first choice. It is best not to use other integer types as a last resort.

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.

Therefore, for example, char-type charactersWThe sequential position of is meaningful, but the same problem is meaningless for the Floating Point Number of 7134.1562. For a real number, you can know exactly whether there is a real number larger than it, but if you want to explore how many real numbers are there before a given real number (this isORDFunction.

Real types are not used much in user interface programming, But Delphi supports real types in various aspects, including database support. Because it supports the IEEE floating point algorithm standard, the Object Pascal language is perfect for all kinds of numerical computing programming. If you are interested in this part, you can refer to the arithmetic functions provided by Delphi in the system unit (for details, see Delphi help ).

Note:: Delphi hasMathUnit, which defines some advanced mathematical routines, including trigonometric functions (suchArccoshFunctions), financial functions (suchInterestpaymentFunctions) and statistical functions (suchMeanandstddevProcess ). Some routines sound strange, suchMomentskewkurtosisRoutine. What is it? Check it for yourself.

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:

 
TypeTdatetime =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.

To show how to use the date and time type and Related Routines, I created a simple example timenow. In this example, a button and a ListBox are set in the main form ). When execution starts, the program automatically calculates and displays the current time and date. Each time you click a button, the start time and end time of the program are displayed.

The oncreate Event code of the form is listed below:

 
ProcedureTformtimenow. formcreate (Sender: tobject );BeginStarttime: = now; listbox1.items. Add (timetostr (starttime); listbox1.items. Add (datetostr (starttime); listbox1.items. Add ('Press button for elapsed time');End;

The now function is called in the first sentence. This function returns the current date and time, and its value is saved in the starttime variable. The starttime variable is the full variable. Its declaration is as follows:

 
VaRFormtimenow: tformtimenow; starttime: tdatetime;

I only added the second statement. The first one was automatically added by Delphi. The Default Code is as follows:

 
VaRForm1: tform1;

The Declaration is automatically updated after the form name is changed. Using Full variables is actually not the best method. A better method is to use private fields of the Form class, which involves object-oriented programming technology.

The following three statements add three entries to the list box on the left of the form. The result is shown in Figure 3.3. The first line in the list box displays the time string of the tdatetime value, the second line shows the date part of the same value, and the last line shows a simple prompt.

Figure 3.3: output at timenow startup

When you click the elapsed button, the third line of string is replaced by the computing result of the program:

ProcedureTformtimenow. buttonelapsedclick (Sender: tobject );VaRStoptime: tdatetime;BeginStoptime: = now; listbox1.items [2]: = formatdatetime ('Hh: NN: ss', Stoptime-starttime );End;

The code re-calculates the current time and shows the time difference between the current time and the start time of the program. The calculated value in other events is used. Therefore, the value must be saved to the full variable. In fact, it is best to use class-based variables.

Note:: The index number of ListBox used in the code above is 2, and it represents the display output of the third row, the reason is that the data items of ListBox are counted from scratch: the first item is 0, the second item is 1, the third item is 2, and so on. This aspect is further discussed in detail when arrays are involved.

In addition to calling timetostr and datetostr, the powerful formatdatetime function is also used in the above example (for details about formatting parameters, see the Delphi help file ). Note that when the time and date are converted into strings, the conversion format depends on the Windows system settings. Delphi reads these values from the system and copies them to several full constants declared in the sysutils unit. For example:

Dateseparator: Char; optional dateformat: string; longdateformat: string; timeseparator: Char; timeamstring: string; timepmstring: string; required timeformat: string; longtimeformat: string; required monthnames: array [1 .. 12]OfString; longmonthnames: array [1 .. 12]OfString; daynames: array [1 .. 7]OfString; longdaynames: array [1 .. 7]OfString;

Most full constants are related to currency and floating-point formatting.Currency and date/time formatting VariablesUnder the topic, you can find the complete list.

Note:: There is a datetimepicker control in Delphi, which provides a common way to select a date, that is, to select a date from a calendar.

Specific windows types

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 chapter 9.

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:

 
VaRN: integer; C: Char; B: Boolean;BeginN: = 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.

Conclusion

This chapter discusses the basic data types of Pascal. Pascal also has a very important feature: it allows programmers to customize data types, known as "user-defined data types", which will be discussed in the next chapter.

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.