Compile Pascal code

Source: Internet
Author: User
Tags integer division
Note

In PASCAL, annotations are enclosed in braces or parentheses with asterisks. Delphi also recognizes C ++-style comments, that is, the comments are placed behind the double slashes. For example

 
{This is a comment} (* this is another comment *) // This is a comment up to the end of the line

The first method is simple and widely used. The second method is widely used in Europe because the European keyboard lacks braces; the third method of annotation is borrowed from C ++, which is only available in the 32-bit version of Delphi.CodeIt is useful when adding short comments.

In this book, I use italic to represent comments and bold to represent keywords, which is consistent with the default Delphi syntax style.

The preceding three annotations are useful for nested annotations. For example, if you want to cancel a piece of code and the code line contains a real comment line, the same comment method is incorrect:

 
{... Code {comment, creating problems}... code}

The correct method is to insert the second annotation method:

 
{... Code // This comment is OK... code}

Note:: If the left braces or parentheses-asterisks are followed by the dollar sign ($), the content is a compilation command, for example, {$ x + }.

In fact, the Compilation instruction is still annotated. For example, {$ x + This is a comment} is valid. This is both an effective Compilation instruction and a comment, although wiseProgramNote that the compilation instructions and comments are separated.

Use uppercase letters

The PASCAL Compiler (unlike compilers in other languages) does not consider the case sensitivity of characters. Therefore, the identifiers myname, and myname are identical. In general, this is a major advantage of Pascal, because in case-sensitive languages, many syntax errors are caused by incorrect capital statements.

Note:The Register process in the control package must start with an uppercase letter R, because it must be compatible with C ++ builder.

However, the case sensitivity is also inconvenient: First, you must note that the case-insensitive identifiers are actually the same to avoid using them as different elements. Second, you must try to maintain consistency in upper case to improve code readability.

Consistency in uppercase is not mandatory by the compiler, but it is a good habit to maintain consistency in uppercase. A common method is to uppercase the first letter of each identifier. If an identifier is composed of several words (spaces cannot be inserted in the middle), the first letter of each word should be large:

Mylongidentifiermyverylongandalmoststupididentifier

In addition, the compiler does not compile spaces, blank lines, and tab-key spaces in the Code. These elements are called spaces. They are only used to improve the readability of the code and do not affect the compilation process.

Unlike basic, the Pascal statement allows a branch to write, which splits a long command into two or more code lines. The disadvantage of allowing statement branches (at least for many basic programmers) is that at the end of a statement, you cannot forget the extra points. More specifically, you must remember to separate the statement from the statement that comes next to it. The only limit of statement branches is that strings cannot be cross-row.

There are no established rules for the use of space and statement branches. The following are some experiences:

    • In the Delphi code editor, there is a vertical line (right margin). You can set the right line to 60 or 70 characters. If you use this line as the benchmark and the Code does not exceed this limit, the code printed on the paper looks nice. Otherwise, the print duration statement will be randomly divided, or even broken in the middle of a word.
    • When a function or process has multiple parameters, we usually place the parameters on different rows.
    • You can leave a blank line before the comment line, or divide long code sentences into smaller parts, which can improve the readability of the Code.
    • Function call parameters are separated by spaces. Operators in expressions are also better separated by spaces. Some programmers may disagree with these proposals, but I insist that space is free and you do not have to pay for space. Why not?

Optimize Layout

The last suggestion about the coding style is: Try to use blank spaces to optimize the layout. This is easy to implement. When writing a compound sentence, the above sentence is used as a reference. The next sentence is indented to the right with two spaces, and the compound sentence embedded with four spaces is indented. For example:

 
If...ThenStatement;If...ThenBeginStatement1; statement2;End;If...ThenBeginIf...ThenStatement1; statement2;End;

Similar indent formats are commonly used in variable or data type names, and can also be used for statement continuation:

 
TypeLetters =SetChar;VaRName: string;Begin{Long comment and long statement, going on in the following line and indented two spaces}Messagedlg ('This is a message', Mtinformation, [mbok], 0 );

The above code writing format is only for you to discuss, so that the code can be easier to read, in fact, the code format does not affect the compilation results. In the examples and code segments of this book, I always stick to the above Code style.Source codeThe manual and help examples adopt similar formatting styles.

Highlight Pascal Elements

To make the Pascal code easier to read and write, the color setting function of the Pascal element is added in the Delphi Editor, that is, the editor uses different colors to represent different Pascal elements. By default, keywords are in bold, and strings and comments are in blue (and often italic ).

Displaying different Pascal elements in different colors is very advantageous for reserved words, comments, and strings, because after coloring, you can see the spelling keyword, the string that does not end normally, and the multi-line comments at a glance.

Use the color page in the Editor Environment option dialog box to easily customize the colors of various Pascal elements (see figure 2.1 ). If you work alone, you can select your preferred color. If you are working with other programmers, you should use a uniform standard color. I feel really uncomfortable using colors that I don't like on the same computer.

Figure 2.1 Edit Environment dialog box

Note:: In this book, I chose a color scheme to display the source code list, hoping to make the code easier to read.

Use a Code Template

In Delphi 3, the new function "code template" is added for code editing ". Because the same set of keywords are often repeatedly typed when writing Pascal statements, Borland developed a new function named "code template, the code template contains the complete code that corresponds to the Code scaling form. You enter the scaling code and press Ctrl + J to display the complete code. For example, if you enter arrayd and press Ctrl + J, the Delphi editor will extend your text:

 
Array[0 ..]Of;

Because the same code structure usually has multiple styles in a predefined code template, the scaling form in the template generally has a suffix letter for you to choose. In addition, you can enter only the first few letters in the scaling form. If you enter AR and press Ctrl + J, a menu is displayed in the editor, the Code Scaling Options are listed in the menu, as shown in figure 2.2.

Figure 2.2 code template options

Code templates can be customized, that is, you can modify existing templates or add common code segments. The '|' character usually appears in the Code text entered by the code template. It indicates the position where the cursor should jump after the template code is entered. That is to say, you should start inputting the code at this position, write the code.

Programming statement

Once defined, you can use the identifiers in the statements and expressions that make up the statements. Pascal provides many statements and expressions. First, let's look at the keywords, expressions, and operators.

Keywords

The keyword is the reserved identifier of Object Pascal, which has a special meaning in the language. Reserved Words cannot be used as identifiers, nor should they be used as identifiers, even if the compiler permits them. In reality, you should not use any keywords as identifiers.

Table 2.1 is a complete list of special identifiers in the object-oriented PASCAL Language (Delphi 4), including keywords and reserved words.

Table 2.1: keywords and reserved words in the object-oriented PASCAL Language

 

Keywords Function
Absolute Command (variable)
Abstract Command (method)
And Operator (Boolean)
Array Type
As Operator (rtti)
ASM Statement
Cycler Backward compatibility (assembly)
At Statement (Exception Handling)
Automatic Access Category character (class)
Begin Block tag
Case Statement
Cdecl Function call Protocol
Class Type
Const Declaration or command (parameter)
Constructor Special Method
Contains Operator (SET)
Default Command (attribute)
Destructor Special Method
Dispid Dispinterface category
Dispinterface Type
Div Operator
Do Statement
Downto Statement ()
Dynamic Command (method)
Else Statement (if or case)
End Block tag
Except Statement (Exception Handling)
Export Backward compatibility (class)
Exports Statement
External Commands (functions)
Far Backward compatibility (class)
File Type
Finalization UNIT structure
Finally Statement (Exception Handling)
For Statement
Forward Function commands
Function Statement
Goto Statement
If Statement
Implementation UNIT structure
Implements Command (attribute)
In Operator (SET)-Engineering Structure
Index Command (dipinterface Interface)
Inherited Statement
Initialization UNIT structure
Inline Backward compatible (see ASM)
Interface Type
Is Operator (rtti)
Label Statement
Library Program Structure
Message Command (method)
MoD Operator (Mathematics)
Name Commands (functions)
Near Backward compatibility (class)
Nil Value
Nodefault Command (attribute)
Not Operator (Boolean)
Object Backward compatibility (class)
Of Statement (CASE)
On Statement (Exception Handling)
Or Operator (Boolean)
Out Command (parameter)
Overload Function commands
Override Function commands
Package Program structure (control package)
Packed Command (record)
Pascal Function call Protocol
Private Class)
Procedure Statement
Program Program Structure
Property Statement
Protected Access Category character (class)
Public Access Category character (class)
Published Access Category character (class)
Raise Statement (Exception Handling)
Read Attribute category
Readonly Dispatch interface category
Record Type
Register Function call Protocol
Reintroduce Function commands
Repeat Statement
Requires Program structure (control package)
Resident Commands (functions)
Resourcestring Type
Safecall Function call Protocol
Set Type
SHL Operator (Mathematics)
SHR Operator (Mathematics)
Stdcall Function call Protocol
Stored Command (attribute)
String Type
Then Statement (IF)
Threadvar Statement
To Statement ()
Try Statement (Exception Handling)
Type Statement
Unit UNIT structure
Until Statement
Uses UNIT structure
VaR Statement
Virtual Command (method)
While Statement
With Statement
Write Attribute category
Writeonly Dispatch interface category
XOR Operator (Boolean)

Expressions and operators

There is no common method for creating an expression, because it depends on the operators used. Pascal includes logical operators, Arithmetic Operators, boolean operators, Relational operators, and set operators. Expressions can be used to determine the value assigned to a variable, calculate the parameters of a function or process, or determine a condition. expressions can also contain function calls. An expression is an operation on the value of an identifier rather than the identifier itself.

AllProgramming LanguageAll expressions in are valid combinations of constants, variables, values, operators, and function values. Expressions can be passed to values of a process or function, but cannot be passed to reference parameters of a process or function.

Operator and its priority

If you have written a program before, you already know what the expression is. Here I will talk about the special part of the Pascal OPERATOR: Operator priority. Table 2.2 lists operators in Pascal by priority group.

Unlike most programming languages, the and or operators in Pascal have higher priority than Relational operators. Therefore, if your code is a <B and c <D, the compiler first compiles the and operator, leading to compilation errors. Therefore, you should enclose each <expression in parentheses: (A <B) and (C <D ).

When the same operator is used for different data types, it has different functions. For example, operator + can calculate the sum of two numbers, connect two strings, calculate the union of the two sets, or even add an offset to the pchar pointer. However, you cannot add two characters in the C language.

Another special operator is Div. In Pascal, you can use/to calculate the quotient of two numbers (real numbers or integers), and you can always get a real result. If you want to calculate the quotient of two integers and want an integer result, you need to use the DIV operator.

Table 2.2: operators and their priorities in Pascal

 

Single Object operator (highest priority)
@ Get the address of a variable or function (returns a pointer)
Not Logical or bitwise Inversion
Multiplication and division Operators
* Multiply or set intersection
/ Floating Point Division
Div Integer Division
MoD Modulo (remainder of Integer Division)
As Program running stage type conversion (rtti operator)
And Sum of logic or by bit
SHL Shift left by bit
SHR Shift right by bit
Addition and subtraction Operators
+ Add an offset to the sum, set union, string connection, or pointer.
- Subtract, set difference set, or pointer to reduce an offset
Or Logical or bitwise OR operation
XOR Logical or bitwise exclusive or operation
Relational and comparison operators (lowest priority)
= Determine if it is equal
<> Judge whether it is not equal
< Judge whether it is less
> Determine whether the value is greater
<= Determines whether it is less than or equal to, or whether it is a subset of a set.
> = Determines whether it is greater than or equal to, or whether it is the parent set of a set
In Determine whether a member is a set Member
Is Determine whether the object type is compatible (another rtti operator)

Set Operators

The Set operators include sum (+), difference (-), intersection (*), member detection (in), and Relational operators. To add an element to a set, you can use the set and perform operations. The following is an example of Delphi for font selection:

Style: = style + [fsbold]; style: = style + [fsbold, fsitalic]-[fsunderline];

Another method is to use standard procedures include and exclude, which are more efficient (but cannot be used for set type attributes of controls, because only one element can be manipulated ):

 
Include (style, fsbold );

Conclusion

We have learned about the basic layout of the PASCAL program from the above content. Next we will explore its details. Start with the predefined and custom data types, and then use keywords to organize programming statements.

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.