Pascal is a general-purpose, high-level language that was originally developed by Niklaus Wirth in the early 1970s. It was developed for teaching programming as a systematic discipline and to develop reliable and efficient programs. Show
Pascal is Algol-based language and includes many constructs of Algol. Algol 60 is a subset of Pascal. Pascal offers several data types and programming structures. It is easy to understand and maintain the Pascal programs. Pascal has grown in popularity in the teaching and academics arena for various reasons:
Features of the Pascal LanguagePascal has the following features −
Facts about Pascal
Why to use Pascal?Pascal allows the programmers to define complex structured data types and build dynamic and recursive data structures, such as lists, trees and graphs. Pascal offers features like records, enumerations, subranges, dynamically allocated variables with associated pointers and sets. Pascal allows nested procedure definitions to any level of depth. This truly provides a great programming environment for learning programming as a systematic discipline based on the fundamental concepts. Among the most amazing implementations of Pascal are −
Pascal - Environment Set UpThere are several Pascal compilers and interpreters available for general use. Among these are −
We will be using Free Pascal in these tutorials. You can download Free Pascal for your operating system from the link: Download Free Pascal Installing Free Pascal on LinuxThe Linux distribution of Free Pascal comes in three forms −
Installation code for the .rpm version:: rpm -i fpc-X.Y.Z-N.ARCH.rpm Where X.Y.Z is the version number of the .rpm file, and ARCH is one of the supported architectures (i386, x86_64, etc.). Installation code for the Debian version (like Ubuntu) − dpkg -i fpc-XXX.deb Where XXX is the version number of the .deb file. For details read: Free Pascal Installation Guide Installing Free Pascal on MacIf you use Mac OS X, the easiest way to use Free Pascal is to download the Xcode development environment from Apple's web site and follow the simple installation instructions. Once you have Xcode setup, you will be able to use the Free Pascal compiler. Installing Free Pascal on WindowsFor Windows, you will download the Windows installer, setup.exe. This is a usual installation program. You need to take the following steps for installation −
For details read: Free Pascal Installation Guide Text EditorThis will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for Pascal programs are typically named with the extension .pas. Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it. Pascal - Program StructuresBefore we study basic building blocks of the Pascal programming language, let us look a bare minimum Pascal program structure so that we can take it as a reference in upcoming chapters. Pascal Program StructureA Pascal program basically consists of the following parts −
Every pascal program generally has a heading statement, a declaration and an execution part strictly in that order. Following format shows the basic syntax for a Pascal program − program {name of the program} uses {comma delimited names of libraries you use} const {global constant declaration block} var {global variable declaration block} function {function declarations, if any} { local variables } begin ... end; procedure { procedure declarations, if any} { local variables } begin ... end; begin { main program block starts} ... end. { the end of main program block } Pascal Hello World ExampleFollowing is a simple pascal code that would print the words "Hello, World!" − program HelloWorld; uses crt; ( Here the main program block starts ) begin writeln('Hello, World!'); readkey; end. This will produce following result − Hello, World! Let us look various parts of the above program −
Compile and Execute Pascal Program
$ fpc hello.pas Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64 Copyright (c) 1993-2011 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling hello.pas Linking hello 8 lines compiled, 0.1 sec $ ./hello Hello, World! Make sure that free pascal compiler fpc is in your path and that you are running it in the directory containing source file hello.pas. Pascal - Basic SyntaxYou have seen a basic structure of pascal program, so it will be easy to understand other basic building blocks of the pascal programming language. VariablesA variable definition is put in a block beginning with a var keyword, followed by definitions of the variables as follows: var A_Variable, B_Variable ... : Variable_Type; Pascal variables are declared outside the code-body of the function which means they are not declared within the begin and end pairs, but they are declared after the definition of the procedure/function and before the begin keyword. For global variables, they are defined after the program header. Functions/ProceduresIn Pascal, a procedure is set of instructions to be executed, with no return value and a function is a procedure with a return value. The definition of function/procedures will be as follows − Function Func_Name(params...) : Return_Value; Procedure Proc_Name(params...); CommentsThe multiline comments are enclosed within curly brackets and asterisks as (* ... *). Pascal allows single-line comment enclosed within curly brackets { ... }. ( This is a multi-line comments and it will span multiple lines. ) { This is a single line comment in pascal } Case SensitivityPascal is a case non-sensitive language, which means you can write your variables, functions and procedure in either case. Like variables A_Variable, a_variable and A_VARIABLE have same meaning in Pascal. Pascal StatementsPascal programs are made of statements. Each statement specifies a definite job of the program. These jobs could be declaration, assignment, reading data, writing data, taking logical decisions, transferring program flow control, etc. For example − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); Reserved Words in PascalThe statements in Pascal are designed with some specific Pascal words, which are called the reserved words. For example, the words, program, input, output, var, real, begin, readline, writeline and end are all reserved words. Following is a list of reserved words available in Pascal. and array begin case const div do downto else end file for function goto if in label mod nil not of or packed procedure program record repeat set then to type until var while with Character set and Identifiers in PascalThe Pascal character set consists of −
The entities in a Pascal program like variables and constants, types, functions, procedures and records, etc., have a name or identifier. An identifier is a sequence of letters and digits, beginning with a letter. Special symbols and blanks must not be used in an identifier. Pascal - Data TypesData types of an entity indicates the meaning, constraints, possible values, operations, functions and mode of storage associated with it. Integer, real, Boolean and character types are referred as standard data types. Data types can be categorized as scalar, pointer and structured data types. Examples of scalar data types are integer, real, Boolean, character, subrange and enumerated. Structured data types are made of the scalar types; for example, arrays, records, files and sets. We will discuss the pointer data types later. Pascal Data TypesPascal data types can be summarized as below in the following diagram − Type DeclarationsThe type declaration is used to declare the data type of an identifier. Syntax of type declaration is − dpkg -i fpc-XXX.deb 0 For example, the following declaration defines the variables days and age as integer type, yes and true as Boolean type, name and city as string type, fees and expenses as real type. dpkg -i fpc-XXX.deb 1 Integer TypesFollowing table gives you details about standard integer types with its storage sizes and value ranges used in Object Pascal − Type Minimum Maximum Format Integer -2147483648 2147483647 signed 32-bit Cardinal 0 4294967295 unsigned 32-bit Shortint -128 127 signed 8-bit Smallint -32768 32767 signed 16-bit Longint -2147483648 2147483647 signed 32-bit Int64 -2^63 2^63 - 1 signed 64-bit Byte 0 255 unsigned 8-bit Word 0 65535 unsigned 16-bit Longword 0 4294967295 unsigned 32-bit ConstantsUse of constants makes a program more readable and helps to keep special quantities at one place in the beginning of the program. Pascal allows numerical, logical, string and character constants. Constants can be declared in the declaration part of the program by specifying the const declaration. Syntax of constant type declaration is follows − dpkg -i fpc-XXX.deb 2 Following are some examples of constant declarations − dpkg -i fpc-XXX.deb 3 All constant declarations must be given before the variable declaration. Enumerated typesEnumerated data types are user-defined data types. They allow values to be specified in a list. Only assignment operators and relational operators are permitted on enumerated data type. Enumerated data types can be declared as follows − dpkg -i fpc-XXX.deb 4 Following are some examples of enumerated type declarations − dpkg -i fpc-XXX.deb 5 The order in which the items are listed in the domain of an enumerated type defines the order of the items. For example, in the enumerated type SUMMER, April comes before May, May comes before June, and so on. The domain of enumerated type identifiers cannot consist of numeric or character constants. Subrange TypesSubrange types allow a variable to assume values that lie within a certain range. For example, if the age of voters should lie between 18 to 100 years, a variable named age could be declared as − dpkg -i fpc-XXX.deb 6 We will look at variable declaration in detail in the next section. You can also define a subrange type using the type declaration. Syntax for declaring a subrange type is as follows − dpkg -i fpc-XXX.deb 7 Following are some examples of subrange type declarations − dpkg -i fpc-XXX.deb 8 Subrange types can be created from a subset of an already defined enumerated type, For example − dpkg -i fpc-XXX.deb 9 Pascal - Variable TypesA variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in Pascal has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Pascal is not case-sensitive, so uppercase and lowercase letters mean same here. Based on the basic types explained in previous chapter, there will be following basic variable types − Basic Variables in PascalSr.No Type & Description 1 Character Typically a single octet (one byte). This is an integer type. 2 Integer The most natural size of integer for the machine. 3 Real A single-precision floating point value. 4 Boolean Specifies true or false logical values. This is also an integer type. 5 Enumerated Specifies a user-defined list. 6 Subrange Represents variables, whose values lie within a range. 7 String Stores an array of characters. Pascal programming language also allows defining various other types of variables, which we will cover in subsequent chapters like Pointer, Array, Records, Sets, and Files, etc. For this chapter, let us study only basic variable types. Variable Declaration in PascalAll variables must be declared before we use them in Pascal program. All variable declarations are followed by the var keyword. A declaration specifies a list of variables, followed by a colon (:) and the type. Syntax of variable declaration is − program {name of the program} uses {comma delimited names of libraries you use} const {global constant declaration block} var {global variable declaration block} function {function declarations, if any} { local variables } begin ... end; procedure { procedure declarations, if any} { local variables } begin ... end; begin { main program block starts} ... end. { the end of main program block } 0 Here, type must be a valid Pascal data type including character, integer, real, boolean, or any user-defined data type, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid variable declarations are shown here − program {name of the program} uses {comma delimited names of libraries you use} const {global constant declaration block} var {global variable declaration block} function {function declarations, if any} { local variables } begin ... end; procedure { procedure declarations, if any} { local variables } begin ... end; begin { main program block starts} ... end. { the end of main program block } 1 In the previous tutorial, we have discussed that Pascal allows declaring a type. A type can be identified by a name or identifier. This type can be used to define variables of that type. For example, dpkg -i fpc-XXX.deb 1 Now, the types so defined can be used in variable declarations − program {name of the program} uses {comma delimited names of libraries you use} const {global constant declaration block} var {global variable declaration block} function {function declarations, if any} { local variables } begin ... end; procedure { procedure declarations, if any} { local variables } begin ... end; begin { main program block starts} ... end. { the end of main program block } 3 Please note the difference between type declaration and var declaration. Type declaration indicates the category or class of the types such as integer, real, etc., whereas the variable specification indicates the type of values a variable may take. You can compare type declaration in Pascal with typedef in C. Most importantly, the variable name refers to the memory location where the value of the variable is going to be stored. This is not so with the type declaration. Variable Initialization in PascalVariables are assigned a value with a colon and the equal sign, followed by a constant expression. The general form of assigning a value is − program {name of the program} uses {comma delimited names of libraries you use} const {global constant declaration block} var {global variable declaration block} function {function declarations, if any} { local variables } begin ... end; procedure { procedure declarations, if any} { local variables } begin ... end; begin { main program block starts} ... end. { the end of main program block } 4 By default, variables in Pascal are not initialized with zero. They may contain rubbish values. So it is a better practice to initialize variables in a program. Variables can be initialized (assigned an initial value) in their declaration. The initialization is followed by the var keyword and the syntax of initialization is as follows − program {name of the program} uses {comma delimited names of libraries you use} const {global constant declaration block} var {global variable declaration block} function {function declarations, if any} { local variables } begin ... end; procedure { procedure declarations, if any} { local variables } begin ... end; begin { main program block starts} ... end. { the end of main program block } 5 Some examples are − program {name of the program} uses {comma delimited names of libraries you use} const {global constant declaration block} var {global variable declaration block} function {function declarations, if any} { local variables } begin ... end; procedure { procedure declarations, if any} { local variables } begin ... end; begin { main program block starts} ... end. { the end of main program block } 6 Let us look at an example, which makes use of various types of variables discussed so far − program {name of the program} uses {comma delimited names of libraries you use} const {global constant declaration block} var {global variable declaration block} function {function declarations, if any} { local variables } begin ... end; procedure { procedure declarations, if any} { local variables } begin ... end; begin { main program block starts} ... end. { the end of main program block } 7 When the above code is compiled and executed, it produces the following result − program {name of the program} uses {comma delimited names of libraries you use} const {global constant declaration block} var {global variable declaration block} function {function declarations, if any} { local variables } begin ... end; procedure { procedure declarations, if any} { local variables } begin ... end; begin { main program block starts} ... end. { the end of main program block } 8 Enumerated VariablesYou have seen how to use simple variable types like integer, real and boolean. Now, let's see variables of enumerated type, which can be defined as − program {name of the program} uses {comma delimited names of libraries you use} const {global constant declaration block} var {global variable declaration block} function {function declarations, if any} { local variables } begin ... end; procedure { procedure declarations, if any} { local variables } begin ... end; begin { main program block starts} ... end. { the end of main program block } 9 When you have declared an enumerated type, you can declare variables of that type. For example, program HelloWorld; uses crt; ( Here the main program block starts ) begin writeln('Hello, World!'); readkey; end. 0 The following example illustrates the concept − program HelloWorld; uses crt; ( Here the main program block starts ) begin writeln('Hello, World!'); readkey; end. 1 When the above code is compiled and executed, it produces the following result − program HelloWorld; uses crt; ( Here the main program block starts ) begin writeln('Hello, World!'); readkey; end. 2 Subrange VariablesSubrange variables are declared as − program HelloWorld; uses crt; ( Here the main program block starts ) begin writeln('Hello, World!'); readkey; end. 3 Examples of subrange variables are − program HelloWorld; uses crt; ( Here the main program block starts ) begin writeln('Hello, World!'); readkey; end. 4 The following program illustrates the concept − program HelloWorld; uses crt; ( Here the main program block starts ) begin writeln('Hello, World!'); readkey; end. 5 When the above code is compiled and executed, it produces the following result − program HelloWorld; uses crt; ( Here the main program block starts ) begin writeln('Hello, World!'); readkey; end. 6 Pascal - ConstantsA constant is an entity that remains unchanged during program execution. Pascal allows only constants of the following types to be declared −
Declaring ConstantsSyntax for declaring constants is as follows − program HelloWorld; uses crt; ( Here the main program block starts ) begin writeln('Hello, World!'); readkey; end. 7 The following table provides examples of some valid constant declarations − Real type constant Sr.No Constant Type & Examples 1 Ordinal(Integer)type constant valid_age = 21; 2 Set type constant Vowels = set of (A,E,I,O,U); 3 Pointer type constant P = NIL; 4 e = 2.7182818; velocity_light = 3.0E+10; 5 Character type constant Operator = '+'; 6 String type constant president = 'Johnny Depp'; The following example illustrates the concept − program HelloWorld; uses crt; ( Here the main program block starts ) begin writeln('Hello, World!'); readkey; end. 8 When the above code is compiled and executed, it produces the following result − program HelloWorld; uses crt; ( Here the main program block starts ) begin writeln('Hello, World!'); readkey; end. 9 Observe the formatting in the output statement of the program. The variable c is to be formatted with total number of digits 7 and 2 digits after the decimal sign. Pascal allows such output formatting with the numerical variables. Pascal - OperatorsAn operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Pascal allows the following types of operators −
Let us discuss the arithmetic, relational, Boolean and bit operators one by one. We will discuss the set operators and string operations later. Arithmetic OperatorsFollowing table shows all the arithmetic operators supported by Pascal. Assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example + Adds two operands A + B will give 30 - Subtracts second operand from the first A - B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by denominator B / A will give 2 % Modulus Operator and remainder of after an integer division B % A will give 0 Relational OperatorsFollowing table shows all the relational operators supported by Pascal. Assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example = Checks if the values of two operands are equal or not, if yes, then condition becomes true. (A = B) is not true. <> Checks if the values of two operands are equal or not, if values are not equal, then condition becomes true. (A <> B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes, then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes, then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes, then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes, then condition becomes true. (A <= B) is true. Boolean OperatorsFollowing table shows all the Boolean operators supported by Pascal language. All these operators work on Boolean operands and produce Boolean results. Assume variable A holds true and variable B holds false, then − Show Examples Operator Description Example and Called Boolean AND operator. If both the operands are true, then condition becomes true. (A and B) is false. and then It is similar to the AND operator, however, it guarantees the order in which the compiler evaluates the logical expression. Left to right and the right operands are evaluated only when necessary. (A and then B) is false. or Called Boolean OR Operator. If any of the two operands is true, then condition becomes true. (A or B) is true. or else It is similar to Boolean OR, however, it guarantees the order in which the compiler evaluates the logical expression. Left to right and the right operands are evaluated only when necessary. (A or else B) is true. not Called Boolean NOT Operator. Used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. not (A and B) is true. Bit OperatorsBitwise operators work on bits and perform bit-by-bit operation. All these operators work on integer operands and produces integer results. The truth table for bitwise and (&), bitwise or (|), and bitwise not (~) are as follows − p q p & q p | q ~p ~q 0 0 0 0 1 1 0 1 0 1 1 0 1 1 1 1 0 0 1 0 0 1 0 1 Assume if A = 60; and B = 13; now in binary format they will be as follows − A = 0011 1100 B = 0000 1101 ----- A&B = 0000 1100 A^B = 0011 0001 ~A = 1100 0011 The Bitwise operators supported by Pascal are listed in the following table. Assume variable A holds 60 and variable B holds 13, then: Show Examples Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12, which is 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61, which is 0011 1101 ! Binary OR Operator copies a bit if it exists in either operand. Its same as | operator. (A ! B) will give 61, which is 0011 1101 ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) will give -61, which is 1100 0011 in 2's complement form due to a signed binary number. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240, which is 1111 0000 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15, which is 0000 1111 Please note that different implementations of Pascal differ in bitwise operators. Free Pascal, the compiler we used here, however, supports the following bitwise operators − Operators Operations not Bitwise NOT and Bitwise AND or Bitwise OR xor Bitwise exclusive OR shl Bitwise shift left shr Bitwise shift right << Bitwise shift left >> Bitwise shift right Operators Precedence in PascalOperator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. Show Examples Operator Precedence ~, not, Highest *, /, div, mod, and, & |, !, +, -, or, =, <>, <, <=, >, >=, in or else, and then Lowest Pascal - Decision MakingDecision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − Pascal programming language provides the following types of decision making statements. Click the following links to check their detail. Sr.No Statement & Description 1 if - then statement An if - then statement consists of a boolean expression followed by one or more statements. 2 If-then-else statement An if - then statement can be followed by an optional else statement, which executes when the boolean expression is false. 3 nested if statements You can use one if or else if statement inside another if or else if statement(s). 4 case statement A case statement allows a variable to be tested for equality against a list of values. 5 case - else statement It is similar to the if-then-else statement. Here, an else term follows the case statement. 6 nested case statements You can use one case statement inside another case statement(s). Pascal - LoopsThere may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − Pascal programming language provides the following types of loop constructs to handle looping requirements. Click the following links to check their details. Sr.No Loop Type & Description 1 while-do loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2 for-do loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 3 repeat-until loop Like a while statement, except that it tests the condition at the end of the loop body. 4 nested loops You can use one or more loop inside any another while, for or repeat until loop. Loop Control StatementsLoop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Pascal supports the following control statements. Click the following links to check their details. Sr.No Control Statement & Description 1 break statement Terminates the loop or case statement and transfers execution to the statement immediately following the loop or case statement. 2 continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. 3 goto statement Transfers control to the labeled statement. Though it is not advised to use goto statement in your program. Pascal - FunctionsSubprogramsA subprogram is a program unit/module that performs a particular task. These subprograms are combined to form larger programs. This is basically called the 'Modular design.' A subprogram can be invoked by a subprogram/program, which is called the calling program. Pascal provides two kinds of subprograms −
FunctionsA function is a group of statements that together perform a task. Every Pascal program has at least one function, which is the program itself, and all the most trivial programs can define additional functions. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. Pascal standard library provides numerous built-in functions that your program can call. For example, function AppendStr() appends two strings, function New() dynamically allocates memory to variables and many more functions. Defining a FunctionIn Pascal, a function is defined using the function keyword. The general form of a function definition is as follows − Hello, World! 0 A function definition in Pascal consists of a function header, local declarations and a function body. The function header consists of the keyword function and a name given to the function. Here are all the parts of a function −
Following is an example showing how to define a function in pascal − Hello, World! 1 Function DeclarationsA function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts − Hello, World! 2 For the above-defined function max(), following is the function declaration − Hello, World! 3 Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function. Calling a FunctionWhile creating a function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, program control is transferred to the called function. A called function performs defined task, and when its return statement is executed or when it last end statement is reached, it returns program control back to the main program. To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. Following is a simple example to show the usage − Hello, World! 4 When the above code is compiled and executed, it produces the following result − Hello, World! 5 Pascal - ProceduresProcedures are subprograms that, instead of returning a single value, allow to obtain a group of results. Defining a ProcedureIn Pascal, a procedure is defined using the procedure keyword. The general form of a procedure definition is as follows − Hello, World! 6 A procedure definition in Pascal consists of a header, local declarations and a body of the procedure. The procedure header consists of the keyword procedure and a name given to the procedure. Here are all the parts of a procedure −
Following is the source code for a procedure called findMin(). This procedure takes 4 parameters x, y, z and m and stores the minimum among the first three variables in the variable named m. The variable m is passed by reference (we will discuss passing arguments by reference a little later) − Hello, World! 7 Procedure DeclarationsA procedure declaration tells the compiler about a procedure name and how to call the procedure. The actual body of the procedure can be defined separately. A procedure declaration has the following syntax − Hello, World! 8 Please note that the name of the procedure is not associated with any type. For the above defined procedure findMin(), following is the declaration − Hello, World! 9 Calling a ProcedureWhile creating a procedure, you give a definition of what the procedure has to do. To use the procedure, you will have to call that procedure to perform the defined task. When a program calls a procedure, program control is transferred to the called procedure. A called procedure performs the defined task, and when its last end statement is reached, it returns the control back to the calling program. To call a procedure, you simply need to pass the required parameters along with the procedure name as shown below − $ fpc hello.pas Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64 Copyright (c) 1993-2011 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling hello.pas Linking hello 8 lines compiled, 0.1 sec $ ./hello Hello, World! 0 When the above code is compiled and executed, it produces the following result − $ fpc hello.pas Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64 Copyright (c) 1993-2011 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling hello.pas Linking hello 8 lines compiled, 0.1 sec $ ./hello Hello, World! 1 Recursive SubprogramsWe have seen that a program or subprogram may call another subprogram. When a subprogram calls itself, it is referred to as a recursive call and the process is known as recursion. To illustrate the concept, let us calculate the factorial of a number. Factorial of a number n is defined as − $ fpc hello.pas Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64 Copyright (c) 1993-2011 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling hello.pas Linking hello 8 lines compiled, 0.1 sec $ ./hello Hello, World! 2 The following program calculates the factorial of a given number by calling itself recursively. $ fpc hello.pas Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64 Copyright (c) 1993-2011 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling hello.pas Linking hello 8 lines compiled, 0.1 sec $ ./hello Hello, World! 3 When the above code is compiled and executed, it produces the following result − $ fpc hello.pas Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64 Copyright (c) 1993-2011 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling hello.pas Linking hello 8 lines compiled, 0.1 sec $ ./hello Hello, World! 4 Following is another example, which generates the Fibonacci Series for a given number using a recursive function − $ fpc hello.pas Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64 Copyright (c) 1993-2011 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling hello.pas Linking hello 8 lines compiled, 0.1 sec $ ./hello Hello, World! 5 When the above code is compiled and executed, it produces the following result − $ fpc hello.pas Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64 Copyright (c) 1993-2011 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling hello.pas Linking hello 8 lines compiled, 0.1 sec $ ./hello Hello, World! 6 Arguments of a SubprogramIf a subprogram (function or procedure) is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the subprogram. The formal parameters behave like other local variables inside the subprogram and are created upon entry into the subprogram and destroyed upon exit. While calling a subprogram, there are two ways that arguments can be passed to the subprogram − Sr.No Call Type & Description 1 Call by value This method copies the actual value of an argument into the formal parameter of the subprogram. In this case, changes made to the parameter inside the subprogram have no effect on the argument. 2 Call by reference This method copies the address of an argument into the formal parameter. Inside the subprogram, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. By default, Pascal uses call by value to pass arguments. In general, this means that code within a subprogram cannot alter the arguments used to call the subprogram. The example program we used in the chapter 'Pascal - Functions' called the function named max() using call by value. Whereas, the example program provided here (exProcedure) calls the procedure findMin() using call by reference. Pascal - Variable ScopeA scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable cannot be accessed. There are three places, where variables can be declared in Pascal programming language −
Let us explain what are local and global variables and formal parameters. Local VariablesVariables that are declared inside a subprogram or block are called local variables. They can be used only by statements that are inside that subprogram or block of code. Local variables are not known to subprograms outside their own. Following is the example using local variables. Here, all the variables a, b and c are local to program named exLocal. $ fpc hello.pas Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64 Copyright (c) 1993-2011 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling hello.pas Linking hello 8 lines compiled, 0.1 sec $ ./hello Hello, World! 7 When the above code is compiled and executed, it produces the following result − $ fpc hello.pas Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64 Copyright (c) 1993-2011 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling hello.pas Linking hello 8 lines compiled, 0.1 sec $ ./hello Hello, World! 8 Now, let us extend the program little more, let us create a procedure named display, which will have its own set of variables a, b and c and display their values, right from the program exLocal. $ fpc hello.pas Free Pascal Compiler version 2.6.0 [2011/12/23] for x86_64 Copyright (c) 1993-2011 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling hello.pas Linking hello 8 lines compiled, 0.1 sec $ ./hello Hello, World! 9 When the above code is compiled and executed, it produces the following result − var A_Variable, B_Variable ... : Variable_Type; 0 Global VariablesGlobal variables are defined outside of a function, usually on top of the program. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is an example using global and local variables − var A_Variable, B_Variable ... : Variable_Type; 1 When the above code is compiled and executed, it produces the following result − var A_Variable, B_Variable ... : Variable_Type; 2 Please note that the procedure display has access to the variables a, b and c, which are global variables with respect to display as well as its own local variables. A program can have same name for local and global variables but value of local variable inside a function will take preference. Let us change the previous example a little, now the local variables for the procedure display has same names as a, b, c − var A_Variable, B_Variable ... : Variable_Type; 3 When the above code is compiled and executed, it produces the following result − var A_Variable, B_Variable ... : Variable_Type; 4 Pascal - StringsThe string in Pascal is actually a sequence of characters with an optional size specification. The characters could be numeric, letters, blank, special characters or a combination of all. Extended Pascal provides numerous types of string objects depending upon the system and implementation. We will discuss more common types of strings used in programs. You can define a string in many ways −
Pascal provides only one string operator, string concatenation operator (+). ExamplesThe following program prints first four kinds of strings. We will use AnsiStrings in the next example. var A_Variable, B_Variable ... : Variable_Type; 5 When the above code is compiled and executed, it produces the following result − var A_Variable, B_Variable ... : Variable_Type; 6 Following example makes use of few more functions, let's see − var A_Variable, B_Variable ... : Variable_Type; 7 When the above code is compiled and executed, it produces the following result − var A_Variable, B_Variable ... : Variable_Type; 8 Pascal String Functions and ProceduresPascal supports a wide range of functions and procedures that manipulate strings. These subprograms vary implement-wise. Here, we are listing various string manipulating subprograms provided by Free Pascal − Sr.No. Function & Purpose 1 function AnsiCompareStr(const S1: ; const S2:):Integer; Compares two strings 2 function AnsiCompareText(const S1: ; const S2:):Integer; Compares two strings, case insensitive 3 function AnsiExtractQuotedStr(var Src: PChar; Quote: Char):; Removes quotes from string 4 function AnsiLastChar(const S:):PChar; Gets last character of string 5 function AnsiLowerCase(const s:): Converts string to all-lowercase 6 function AnsiQuotedStr(const S: ; Quote: Char):; Quotes a string 7 function AnsiStrComp(S1: PChar;S2: PChar):Integer; Compares strings case-sensitive 8 function AnsiStrIComp(S1: PChar; S2: PChar):Integer; Compares strings case-insensitive 9 function AnsiStrLComp(S1: PChar; S2: PChar; MaxLen: Cardinal):Integer; Compares L characters of strings case sensitive 10 function AnsiStrLIComp(S1: PChar; S2: PChar; MaxLen: Cardinal):Integer; Compares L characters of strings case insensitive 11 function AnsiStrLastChar(Str: PChar):PChar; Gets last character of string 12 function AnsiStrLower(Str: PChar):PChar; Converts string to all-lowercase 13 function AnsiStrUpper(Str: PChar):PChar; Converts string to all-uppercase 14 function AnsiUpperCase(const s:):; Converts string to all-uppercase 15 procedure AppendStr(var Dest: ; const S:); Appends 2 strings 16 procedure AssignStr(var P: PString; const S:); Assigns value of strings on heap 17 function CompareStr(const S1: ; const S2:):Integer; overload; Compares two strings case sensitive 18 function CompareText(const S1: ; const S2:):Integer; Compares two strings case insensitive 19 procedure DisposeStr(S: PString); overload; Removes string from heap 20 procedure DisposeStr(S: PShortString); overload; Removes string from heap 21 function IsValidIdent( const Ident:):Boolean; Is string a valid pascal identifier 22 function LastDelimiter(const Delimiters: ; const S:):Integer; Last occurrence of character in a string 23 function LeftStr(const S: ; Count: Integer):; Gets first N characters of a string 24 function LoadStr(Ident: Integer):; Loads string from resources 25 function LowerCase(const s: ):; overload; Converts string to all-lowercase 26 function LowerCase(const V: variant ):; overload; Converts string to all-lowercase 27 function NewStr(const S:):PString; overload; Allocates new string on heap 28 function RightStr(const S: ; Count: Integer):; Gets last N characters of a string 29 function StrAlloc(Size: Cardinal):PChar; Allocates memory for string 30 function StrBufSize(Str: PChar):SizeUInt; Reserves memory for a string 31 procedure StrDispose(Str: PChar); Removes string from heap 32 function StrPas(Str: PChar):; Converts PChar to pascal string 33 function StrPCopy(Dest: PChar; Source:):PChar; Copies pascal string 34 function StrPLCopy(Dest: PChar; Source: ; MaxLen: SizeUInt):PChar; Copies N bytes of pascal string 35 function UpperCase(const s:):; Converts string to all-uppercase Pascal - BooleansPascal provides data type Boolean that enables the programmers to define, store and manipulate logical entities, such as constants, variables, functions and expressions, etc. Boolean values are basically integer type. Boolean type variables have two pre-defined possible values True and False. The expressions resolving to a Boolean value can also be assigned to a Boolean type. Free Pascal also supports the ByteBool, WordBool and LongBool types. These are of type Byte, Word or Longint, respectively. The value False is equivalent to 0 (zero) and any nonzero value is considered True when converting to a Boolean value. A Boolean value of True is converted to -1 in case it is assigned to a variable of type LongBool. It should be noted that logical operators and, or and not are defined for Boolean data types. Declaration of Boolean Data TypesA variable of Boolean type is declared using the var keyword. var A_Variable, B_Variable ... : Variable_Type; 9 for example, Function Func_Name(params...) : Return_Value; Procedure Proc_Name(params...); 0 ExampleFunction Func_Name(params...) : Return_Value; Procedure Proc_Name(params...); 1 When the above code is compiled and executed, it produces the following result − Function Func_Name(params...) : Return_Value; Procedure Proc_Name(params...); 2 Pascal - ArraysPascal programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number1, number2, ..., and number100, you declare one array variable such as numbers and use numbers[1], numbers[2], and ..., numbers[100] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Please note that if you want a C style array starting from index 0, you just need to start the index from 0, instead of 1. Declaring ArraysTo declare an array in Pascal, a programmer may either declare the type and then create variables of that array or directly declare the array variable. The general form of type declaration of one-dimensional array is − Function Func_Name(params...) : Return_Value; Procedure Proc_Name(params...); 3 Where,
For example, Function Func_Name(params...) : Return_Value; Procedure Proc_Name(params...); 4 Now, velocity is a variable array of vector type, which is sufficient to hold up to 25 real numbers. To start the array from 0 index, the declaration would be − Function Func_Name(params...) : Return_Value; Procedure Proc_Name(params...); 5 Types of Array SubscriptIn Pascal, an array subscript could be of any scalar type like, integer, Boolean, enumerated or subrange, except real. Array subscripts could have negative values too. For example, Function Func_Name(params...) : Return_Value; Procedure Proc_Name(params...); 6 Let us take up another example where the subscript is of character type − Function Func_Name(params...) : Return_Value; Procedure Proc_Name(params...); 7 Subscript could be of enumerated type − Function Func_Name(params...) : Return_Value; Procedure Proc_Name(params...); 8 Initializing ArraysIn Pascal, arrays are initialized through assignment, either by specifying a particular subscript or using a for-do loop. For example − Function Func_Name(params...) : Return_Value; Procedure Proc_Name(params...); 9 Accessing Array ElementsAn element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example − ( This is a multi-line comments and it will span multiple lines. ) { This is a single line comment in pascal } 0 The above statement will take the first element from the array named alphabet and assign the value to the variable a. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays − ( This is a multi-line comments and it will span multiple lines. ) { This is a single line comment in pascal } 1 When the above code is compiled and executed, it produces the following result − ( This is a multi-line comments and it will span multiple lines. ) { This is a single line comment in pascal } 2 Pascal Arrays in DetailArrays are important to Pascal and should need lots of more details. There are following few important concepts related to array which should be clear to a Pascal programmer − Sr.No Concept & Description 1 Multi-dimensional arrays Pascal supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. 2 Dynamic array In this type of arrays, the initial length is zero. The actual length of the array must be set with the standard SetLength function. 3 Packed array These arrays are bit-packed, i.e., each character or truth values are stored in consecutive bytes instead of using one storage unit, usually a word (4 bytes or more). 4 Passing arrays to subprograms You can pass to a subprogram a pointer to an array by specifying the array's name without an index. Pascal - PointersPointers in Pascal are easy and fun to learn. Some Pascal programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect Pascal programmer. Let's start learning them in simple and easy steps. As you know, every variable is a memory location and every memory location has its address defined which can be accessed using the name of the pointer variable, which denotes an address in memory. What Are Pointers?A pointer is a dynamic variable, whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is − ( This is a multi-line comments and it will span multiple lines. ) { This is a single line comment in pascal } 3 The pointer type is defined by prefixing the up-arrow of caret symbol (^) with the base type. The base-type defines the types of the data items. Once a pointer variable is defined to be of certain type, it can point data items of that type only. Once a pointer type has been defined, we can use the var declaration to declare pointer variables. ( This is a multi-line comments and it will span multiple lines. ) { This is a single line comment in pascal } 4 Following are some valid pointer declarations − ( This is a multi-line comments and it will span multiple lines. ) { This is a single line comment in pascal } 5 The pointer variables are dereferenced by using the same caret symbol (). For example, the associated variable referred by a pointer rptr, is rptr. It can be accessed as − ( This is a multi-line comments and it will span multiple lines. ) { This is a single line comment in pascal } 6 The following example will illustrate this concept − ( This is a multi-line comments and it will span multiple lines. ) { This is a single line comment in pascal } 7 When the above code is compiled and executed, it produces the following result − ( This is a multi-line comments and it will span multiple lines. ) { This is a single line comment in pascal } 8 Printing a Memory Address in PascalIn Pascal, we can assign the address of a variable to a pointer variable using the address operator (@). We use this pointer to manipulate and access the data item. However, if for some reason, we need to work with the memory address itself, we need to store it in a word type variable. Let us extend the above example to print the memory address stored in the pointer iptr − ( This is a multi-line comments and it will span multiple lines. ) { This is a single line comment in pascal } 9 When the above code is compiled and executed, it produces the following result − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); 0 NIL PointersIt is always a good practice to assign a NIL value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NIL points to nowhere. Consider the following program − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); 1 When the above code is compiled and executed, it produces the following result − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); 2 To check for a nil pointer you can use an if statement as follows − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); 3 Pascal Pointers in DetailPointers have many but easy concepts and they are very important to Pascal programming. There are following few important pointer concepts, which should be clear to a Pascal programmer − Pascal - RecordsPascal arrays allow you to define type of variables that can hold several data items of the same kind but a record is another user-defined data type available in Pascal which allows you to combine data items of different kinds. Records consist of different fields. Suppose you want to keep track of your books in a library, you might want to track the following attributes about each book −
Defining a RecordTo define a record type, you may use the type declaration statement. The record type is defined as − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); 4 Here is the way you would declare the Book record − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); 5 The record variables are defined in the usual way as readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); 6 Alternatively, you can directly define a record type variable as − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); 7 Accessing Fields of a RecordTo access any field of a record, we use the member access operator (.). The member access operator is coded as a period between the record variable name and the field that we wish to access. Following is the example to explain usage of structure − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); 8 When the above code is compiled and executed, it produces the following result − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); 9 Records as Subprogram ArgumentsYou can pass a record as a subprogram argument in very similar way as you pass any other variable or pointer. You would access the record fields in the similar way as you have accessed in the above example − dpkg -i fpc-XXX.deb 00 When the above code is compiled and executed, it produces the following result − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); 9 Pointers to RecordsYou can define pointers to records in very similar way as you define pointer to any other variable as follows − dpkg -i fpc-XXX.deb 02 Now, you can store the address of a record type variable in the above-defined pointer variable. To declare a variable of the created pointer type, you use the var keyword − dpkg -i fpc-XXX.deb 03 Before using these pointers, you must create storage for a record-name type variable, which will be manipulated by these pointers. dpkg -i fpc-XXX.deb 04 To access the members of a record using a pointer to that record, you must use the ^. operator as follows − dpkg -i fpc-XXX.deb 05 Finally, don't forget to dispose the used storage, when it is no longer in use − dpkg -i fpc-XXX.deb 06 Let us re-write the first example using a pointer to the Books record. Hope this will be easy for you to understand the concept − dpkg -i fpc-XXX.deb 07 When the above code is compiled and executed, it produces the following result − readln (a, b, c); s := (a + b + c)/2.0; area := sqrt(s (s - a)(s-b)*(s-c)); writeln(area); 9 The With StatementWe have discussed that the members of a record can be accessed using the member access operator (.). This way the name of the record variable has to be written every time. The With statement provides an alternative way to do that. Look at the following code snippet taken from our first example − dpkg -i fpc-XXX.deb 09 The same assignment could be written using the With statement as − dpkg -i fpc-XXX.deb 10 Pascal - VariantsPascal supports a unique type of storage named variants. You can assign any simple type of values in a variant variable. The type of a value stored in a variant is only determined at runtime. Almost any simple type can be assigned to variants: ordinal types, string types, int64 types. Structured types such as sets, records, arrays, files, objects and classes are not assignment-compatible with a variant. You can also assign a pointer to a variant. Free Pascal supports variants. Declaring a VariantYou can declare variant type like any other types using the var keyword. The syntax for declaring a variant type is − dpkg -i fpc-XXX.deb 11 Now, this variant variable v can be assigned to almost all simple types including the enumerated types and vice versa. dpkg -i fpc-XXX.deb 12 ExampleThe following example would illustrate the concept − dpkg -i fpc-XXX.deb 13 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 14 Pascal - SetsA set is a collection of elements of same type. Pascal allows defining the set data type. The elements in a set are called its members. In mathematics, sets are represented by enclosing the members within braces{}. However, in Pascal, set elements are enclosed within square brackets [], which are referred as set constructor. Defining Set Types and VariablesPascal Set types are defined as dpkg -i fpc-XXX.deb 15 Variables of set type are defined as dpkg -i fpc-XXX.deb 16 or, dpkg -i fpc-XXX.deb 17 Examples of some valid set type declaration are − dpkg -i fpc-XXX.deb 18 Set OperatorsYou can perform the following set operations on Pascal sets. Sr.No Operations & Descriptions 1 Union This joins two sets and gives a new set with members from both sets. 2 Difference Gets the difference of two sets and gives a new set with elements not common to either set. 3 Intersection Gets the intersection of two sets and gives a new set with elements common to both sets. 4 Inclusion A set P is included in set Q, if all items in P are also in Q but not vice versa. 5 Symmetric difference Gets the symmetric difference of two sets and gives a set of elements, which are in either of the sets and not in their intersection. 6 In It checks membership. Following table shows all the set operators supported by Free Pascal. Assume that S1 and S2 are two character sets, such that − S1 := ['a', 'b', 'c']; S2 := ['c', 'd', 'e']; Operator Description Example + Union of two sets S1 + S2 will give a set ['a', 'b', 'c', 'd', 'e'] - Difference of two sets S1 - S2 will give a set ['a', 'b'] * Intersection of two sets S1 * S2 will give a set ['c'] \>< Symmetric difference of two sets S1 >< S2 will give a set ['a', 'b', 'd', 'e'] = Checks equality of two sets S1 = S2 will give the boolean value False <> Checks non-equality of two sets S1 <> S2 will give the boolean value True <= Contains (Checks if one set is a subset of the other) S1 <= S2 will give the boolean value False Include Includes an element in the set; basically it is the Union of a set and an element of same base type Include (S1, ['d']) will give a set ['a', 'b', 'c', 'd'] Exclude Excludes an element from a set; basically it is the Difference of a set and an element of same base type Exclude (S2, ['d']) will give a set ['c', 'e'] In Checks set membership of an element in a set ['e'] in S2 gives the boolean value True ExampleThe following example illustrates the use of some of these operators − dpkg -i fpc-XXX.deb 19 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 20 Pascal - File HandlingPascal treats a file as a sequence of components, which must be of uniform type. A file's type is determined by the type of the components. File data type is defined as − dpkg -i fpc-XXX.deb 21 Where, the base-type indicates the type of the components of the file. The base type could be anything like, integer, real, Boolean, enumerated, subrange, record, arrays and sets except another file type. Variables of a file type are created using the var declaration − dpkg -i fpc-XXX.deb 22 Following are some examples of defining some file types and file variables − dpkg -i fpc-XXX.deb 23 Creating and Writing to a FileLet us write a program that would create a data file for students' records. It would create a file named students.dat and write a student's data into it − dpkg -i fpc-XXX.deb 24 When compiled and run, the program would create a file named students.dat into the working directory. You can open the file using a text editor, like notepad, to look at John Smith's data. Reading from a FileWe have just created and written into a file named students.dat. Now, let us write a program that would read the student's data from the file − dpkg -i fpc-XXX.deb 25 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 26 Files as Subprogram ParameterPascal allows file variables to be used as parameters in standard and user-defined subprograms. The following example illustrates this concept. The program creates a file named rainfall.txt and stores some rainfall data. Next, it opens the file, reads the data and computes the average rainfall. Please note that, if you use a file parameter with subprograms, it must be declared as a var parameter. dpkg -i fpc-XXX.deb 27 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 28 Text FilesA text file, in Pascal, consists of lines of characters where each line is terminated with an end-of-line marker. You can declare and define such files as − dpkg -i fpc-XXX.deb 29 Difference between a normal file of characters and a text file is that a text file is divided into lines, each terminated by a special end-of-line marker, automatically inserted by the system. The following example creates and writes into a text file named contact.txt − dpkg -i fpc-XXX.deb 30 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 31 Appending to a FileAppending to a file means writing to an existing file that already has some data without overwriting the file. The following program illustrates this − dpkg -i fpc-XXX.deb 32 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 33 File Handling FunctionsFree Pascal provides the following functions/procedures for file handling − Sr.No. Function Name & Description 1 procedure Append(var t: Text); Opens a file in append mode 2 procedure Assign(out f: file; const Name:); Assigns a name to a file 3 procedure Assign(out f: file; p: PChar); Assigns a name to a file 4 procedure Assign(out f: file; c: Char); Assigns a name to a file 5 procedure Assign(out f: TypedFile; const Name:); Assigns a name to a file 6 procedure Assign(out f: TypedFile; p: PChar); Assigns a name to a file 7 procedure Assign(out f: TypedFile; c: Char); Assigns a name to a file 8 procedure Assign(out t: Text; const s:); Assigns a name to a file 9 procedure Assign(out t: Text; p: PChar); Assigns a name to a file 10 procedure Assign(out t: Text; c: Char); Assigns a name to a file 11 procedure BlockRead(var f: file; var Buf; count: Int64; var Result: Int64); Reads data from a file into memory 12 procedure BlockRead(var f: file; var Buf; count: LongInt; var Result: LongInt); Reads data from a file into memory 13 procedure BlockRead(var f: file; var Buf; count: Cardinal; var Result: Cardinal); Reads data from a file into memory 14 procedure BlockRead(var f: file; var Buf; count: Word; var Result: Word); Reads data from a file into memory 15 procedure BlockRead(var f: file; var Buf; count: Word; var Result: Integer); Reads data from a file into memory 16 procedure BlockRead(var f: file; var Buf; count: Int64); Reads data from a file into memory 17 procedure BlockWrite(var f: file; const Buf; Count: Int64; var Result: Int64); Writes data from memory to a file 18 procedure BlockWrite(var f: file; const Buf; Count: LongInt; var Result: LongInt); Writes data from memory to a file 19 procedure BlockWrite(var f: file; const Buf; Count: Cardinal; var Result: Cardinal); Writes data from memory to a file 20 procedure BlockWrite(var f: file; const Buf; Count: Word; var Result: Word); Writes data from memory to a file 21 procedure BlockWrite(var f: file; const Buf; Count: Word; var Result: Integer); Writes data from memory to a file 22 procedure BlockWrite(var f: file; const Buf; Count: LongInt); Writes data from memory to a file 23 procedure Close(var f: file); Closes a file 24 procedure Close(var t: Text); Closes a file 25 function EOF(var f: file):Boolean; Checks for end of file 26 function EOF(var t: Text):Boolean; Checks for end of file 27 function EOF: Boolean; Checks for end of file 28 function EOLn(var t: Text):Boolean; Checks for end of line 29 function EOLn: Boolean; Checks for end of line 30 procedure Erase(var f: file); Deletes file from disk 31 procedure Erase(var t: Text); Deletes file from disk 32 function FilePos( var f: file):Int64; Position in file 33 function FileSize(var f: file):Int64; Size of file 34 procedure Flush(var t: Text); Writes file buffers to disk 35 function IOResult: Word; Returns result of last file IO operation 36 procedure Read(var F: Text; Args: Arguments); Reads from file into variable 37 procedure Read(Args: Arguments); Reads from file into variable 38 procedure ReadLn(var F: Text; Args: Arguments); Reads from file into variable and goto next line 39 procedure ReadLn(Args: Arguments); Reads from file into variable and goto next line 40 procedure Rename(var f: file; const s:); Renames file on disk 41 procedure Rename(var f: file; p: PChar); Renames file on disk 42 procedure Rename(var f: file; c: Char); Renames file on disk 43 procedure Rename(var t: Text; const s); Rename file on disk 44 procedure Rename(var t: Text; p: PChar); Renames file on disk 45 procedure Rename( var t: Text; c: Char); Renames file on disk 46 procedure Reset(var f: file; l: LongInt); Opens file for reading 47 procedure Reset(var f: file); Opens file for reading 48 procedure Reset(var f: TypedFile); Opens file for reading 49 procedure Reset(var t: Text); Opens file for reading 50 procedure Rewrite(var f: file; l: LongInt); Opens file for writing 51 procedure Rewrite(var f: file); Opens file for writing 52 procedure Rewrite(var f: TypedFile); Opens file for writing 53 procedure Rewrite(var t: Text); Opens file for writing 54 procedure Seek(var f: file; Pos: Int64); Sets file position 55 function SeekEOF(var t: Text):Boolean; Sets file position to end of file 56 function SeekEOF: Boolean; Sets file position to end of file 57 function SeekEOLn(var t: Text):Boolean; Sets file position to end of line 58 function SeekEOLn: Boolean; Sets file position to end of line 59 procedure SetTextBuf(var f: Text; var Buf); Sets size of file buffer 60 procedure SetTextBuf(var f: Text; var Buf; Size: SizeInt); Sets size of file buffer 61 procedure Truncate(var F: file); Truncate the file at position 62 procedure Write(Args: Arguments); Writes variable to file 63 procedure Write(var F: Text; Args: Arguments); Write variable to file 64 procedure Writeln(Args: Arguments); Writes variable to file and append newline 65 procedure WriteLn(var F: Text; Args: Arguments); Writes variable to file and append newline Pascal - Memory ManagementThis chapter explains dynamic memory management in Pascal. Pascal programming language provides several functions for memory allocation and management. Allocating Memory DynamicallyWhile doing programming, if you are aware about the size of an array, then it is easy and you can define it as an array. For example, to store a name of any person, it can go max 100 characters so you can define something as follows − dpkg -i fpc-XXX.deb 34 But now, let us consider a situation, where you have no idea about the length of the text you need to store, for example, you want to store a detailed description about a topic. Here, we need to define a pointer to string without defining how much memory is required. Pascal provides a procedure newto create pointer variables. dpkg -i fpc-XXX.deb 35 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 36 Now, if you need to define a pointer with specific number of bytes to be referred by it later, you should use the getmem function or the getmem procedure, which has the following syntax − dpkg -i fpc-XXX.deb 37 In the previous example, we declared a pointer to a string. A string has a maximum value of 255 bytes. If you really don't need that much space, or a larger space, in terms of bytes, getmem subprogram allows specifying that. Let us rewrite the previous example, using getmem − dpkg -i fpc-XXX.deb 38 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 36 So, you have complete control and you can pass any size value while allocating memory unlike arrays, where once you defined the size cannot be changed. Resizing and Releasing MemoryWhen your program comes out, operating system automatically releases all the memory allocated by your program, but as a good practice when you are not in need of memory anymore, then you should release that memory. Pascal provides the procedure dispose to free a dynamically created variable using the procedure new. If you have allocated memory using the getmem subprogram, then you need to use the subprogram freemem to free this memory. The freemem subprograms have the following syntax − dpkg -i fpc-XXX.deb 40 Alternatively, you can increase or decrease the size of an allocated memory block by calling the function ReAllocMem. Let us check the above program once again and make use of ReAllocMem and freemem subprograms. Following is the syntax for ReAllocMem − dpkg -i fpc-XXX.deb 41 Following is an example which makes use of ReAllocMem and freemem subprograms − dpkg -i fpc-XXX.deb 42 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 43 Memory Management FunctionsPascal provides a hoard of memory management functions that is used in implementing various data structures and implementing low-level programming in Pascal. Many of these functions are implementation dependent. Free Pascal provides the following functions and procedures for memory management − S.N Function Name & Description 1 function Addr(X: TAnytype):Pointer; Returns address of variable 2 function Assigned(P: Pointer):Boolean; Checks if a pointer is valid 3 function CompareByte(const buf1; const buf2; len: SizeInt):SizeInt; Compares 2 memory buffers byte per byte 4 function CompareChar(const buf1; const buf2; len: SizeInt):SizeInt; Compares 2 memory buffers byte per byte 5 function CompareDWord(const buf1; const buf2; len: SizeInt):SizeInt; Compares 2 memory buffers byte per byte 6 function CompareWord(const buf1; const buf2; len: SizeInt):SizeInt; Compares 2 memory buffers byte per byte 7 function Cseg: Word; Returns code segment 8 procedure Dispose(P: Pointer); Frees dynamically allocated memory 9 procedure Dispose(P: TypedPointer; Des: TProcedure); Frees dynamically allocated memory 10 function Dseg: Word; Returns data segment 11 procedure FillByte(var x; count: SizeInt; value: Byte); Fills memory region with 8-bit pattern 12 procedure FillChar( var x; count: SizeInt; Value: Byte|Boolean|Char); Fills memory region with certain character 13 procedure FillDWord( var x; count: SizeInt; value: DWord); Fills memory region with 32-bit pattern 14 procedure FillQWord( var x; count: SizeInt; value: QWord); Fills memory region with 64-bit pattern 15 procedure FillWord( var x; count: SizeInt; Value: Word); Fills memory region with 16-bit pattern 16 procedure Freemem( p: pointer; Size: PtrUInt); Releases allocated memory 17 procedure Freemem( p: pointer ); Releases allocated memory 18 procedure Getmem( out p: pointer; Size: PtrUInt); Allocates new memory 19 procedure Getmem( out p: pointer); Allocates new memory 20 procedure GetMemoryManager( var MemMgr: TMemoryManager); Returns current memory manager 21 function High( Arg: TypeOrVariable):TOrdinal; Returns highest index of open array or enumerated 22 function IndexByte( const buf; len: SizeInt; b: Byte):SizeInt; Finds byte-sized value in a memory range 23 function IndexChar( const buf; len: SizeInt; b: Char):SizeInt; Finds char-sized value in a memory range 24 function IndexDWord( const buf; len: SizeInt; b: DWord):SizeInt; Finds DWord-sized (32-bit) value in a memory range 25 function IndexQWord( const buf; len: SizeInt; b: QWord):SizeInt; Finds QWord-sized value in a memory range 26 function Indexword( const buf; len: SizeInt; b: Word):SizeInt; Finds word-sized value in a memory range 27 function IsMemoryManagerSet: Boolean; Is the memory manager set 28 function Low( Arg: TypeOrVariable ):TOrdinal; Returns lowest index of open array or enumerated 29 procedure Move( const source; var dest; count: SizeInt ); Moves data from one location in memory to another 30 procedure MoveChar0( const buf1; var buf2; len: SizeInt); Moves data till first zero character 31 procedure New( var P: Pointer); Dynamically allocate memory for variable 32 procedure New( var P: Pointer; Cons: TProcedure); Dynamically allocates memory for variable 33 function Ofs( var X ):LongInt; Returns offset of variable 34 function ptr( sel: LongInt; off: LongInt):farpointer; Combines segment and offset to pointer 35 function ReAllocMem( var p: pointer; Size: PtrUInt):pointer; Resizes a memory block on the heap 36 function Seg( var X):LongInt; Returns segment 37 procedure SetMemoryManager( const MemMgr: TMemoryManager ); Sets a memory manager 38 function Sptr: Pointer; Returns current stack pointer 39 function Sseg: Word; Returns stack segment register value Pascal - UnitsA Pascal program can consist of modules called units. A unit might consist of some code blocks, which in turn are made up of variables and type declarations, statements, procedures, etc. There are many built-in units in Pascal and Pascal allows programmers to define and write their own units to be used later in various programs. Using Built-in UnitsBoth the built-in units and user-defined units are included in a program by the uses clause. We have already used the variants unit in Pascal - Variants tutorial. This tutorial explains creating and including user-defined units. However, let us first see how to include a built-in unit crt in your program − dpkg -i fpc-XXX.deb 44 The following example illustrates using the crt unit − dpkg -i fpc-XXX.deb 45 It is the same program we used right at the beginning of the Pascal tutorial, compile and run it to find the effects of the change. Creating and Using a Pascal UnitTo create a unit, you need to write the modules or subprograms you want to store in it and save it in a file with .pas extension. The first line of this file should start with the keyword unit followed by the name of the unit. For example − dpkg -i fpc-XXX.deb 46 Following are three important steps in creating a Pascal unit −
The following program creates the unit named calculateArea − dpkg -i fpc-XXX.deb 47 Next, let us write a simple program that would use the unit we defined above − dpkg -i fpc-XXX.deb 48 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 49 Pascal - Date and TimeMost of the softwares you write need implementing some form of date functions returning current date and time. Dates are so much part of everyday life that it becomes easy to work with them without thinking. Pascal also provides powerful tools for date arithmetic that makes manipulating dates easy. However, the actual name and workings of these functions are different for different compilers. Getting the Current Date & TimePascal's TimeToString function gives you the current time in a colon(: ) delimited form. The following example shows how to get the current time − dpkg -i fpc-XXX.deb 50 When the above code was compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 51 The Date function returns the current date in TDateTime format. The TDateTime is a double value, which needs some decoding and formatting. The following program demonstrates how to use it in your program to display the current date − dpkg -i fpc-XXX.deb 52 When the above code was compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 53 The Now function returns the current date and time − dpkg -i fpc-XXX.deb 54 When the above code was compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 55 Free Pascal provides a simple time stamp structure named TTimeStamp, which has the following format − dpkg -i fpc-XXX.deb 56 Various Date & Time FunctionsFree Pascal provides the following date and time functions − Sr.No. Function Name & Description 1 function DateTimeToFileDate(DateTime: TDateTime):LongInt; Converts DateTime type to file date. 2 function DateTimeToStr( DateTime: TDateTime):; Constructs string representation of DateTime 3 function DateTimeToStr(DateTime: TDateTime; const FormatSettings: TFormatSettings):; Constructs string representation of DateTime 4 procedure DateTimeToString(out Result: ;const FormatStr: ;const DateTime: TDateTime); Constructs string representation of DateTime 5 procedure DateTimeToString(out Result: ; const FormatStr: ; const DateTime: TDateTime; const FormatSettings: TFormatSettings); Constructs string representation of DateTime 6 procedure DateTimeToSystemTime(DateTime: TDateTime; out SystemTime: TSystemTime); Converts DateTime to system time 7 function DateTimeToTimeStamp( DateTime: TDateTime):TTimeStamp;Converts DateTime to timestamp 8 function DateToStr(Date: TDateTime):; Constructs string representation of date 9 function DateToStr(Date: TDateTime; const FormatSettings: TFormatSettings):; Constructs string representation of date 10 function Date: TDateTime; Gets current date 11 function DayOfWeek(DateTime: TDateTime):Integer; Gets day of week 12 procedure DecodeDate(Date: TDateTime; out Year: Word; out Month: Word; out Day: Word); Decodes DateTime to year month and day 13 procedure DecodeTime(Time: TDateTime; out Hour: Word; out Minute: Word; out Second: Word; out MilliSecond: Word); Decodes DateTime to hours, minutes and seconds 14 function EncodeDate(Year: Word; Month: Word; Day: Word):TDateTime; Encodes year, day and month to DateTime 15 function EncodeTime(Hour: Word; Minute: Word; Second: Word; MilliSecond: Word):TDateTime; Encodes hours, minutes and seconds to DateTime 16 function FormatDateTime(const FormatStr: ; DateTime: TDateTime):; Returns string representation of DateTime 17 function FormatDateTime(const FormatStr: ; DateTime: TDateTime; const FormatSettings: TFormatSettings):; Returns string representation of DateTime 18 function IncMonth(const DateTime: TDateTime; NumberOfMonths: Integer = 1):TDateTime; Adds 1 to month 19 function IsLeapYear(Year: Word):Boolean; Determines if year is leap year 20 function MSecsToTimeStamp(MSecs: Comp):TTimeStamp; Converts number of milliseconds to timestamp 21 function Now: TDateTime; Gets current date and time 22 function StrToDateTime(const S:):TDateTime; Converts string to DateTime 23 function StrToDateTime(const s: ShortString; const FormatSettings: TFormatSettings):TDateTime; Converts string to DateTime 24 function StrToDateTime(const s: AnsiString; const FormatSettings: TFormatSettings):TDateTime; Converts string to DateTime 25 function StrToDate(const S: ShortString):TDateTime; Converts string to date 26 function StrToDate(const S: Ansistring):TDateTime; Converts string to date 27 function StrToDate(const S: ShortString; separator: Char):TDateTime; Converts string to date 28 function StrToDate(const S: AnsiString; separator: Char):TDateTime; Converts string to date 29 function StrToDate(const S: ShortString; const useformat: ; separator: Char):TDateTime; Converts string to date 30 function StrToDate(const S: AnsiString; const useformat: ; separator: Char):TDateTime; Converts string to date 31 function StrToDate(const S: PChar; Len: Integer; const useformat: ; separator: Char = 0):TDateTime;Converts string to date 32 function StrToTime(const S: Shortstring):TDateTime; Converts string to time 33 function StrToTime(const S: Ansistring):TDateTime; Converts string to time 34 function StrToTime(const S: ShortString; separator: Char):TDateTime; Converts string to time 35 function StrToTime(const S: AnsiString; separator: Char):TDateTime; Converts string to time 36 function StrToTime(const S: ; FormatSettings: TFormatSettings):TDateTime; Converts string to time 37 function StrToTime(const S: PChar; Len: Integer; separator: Char = 0):TDateTime;Converts string to time 38 function SystemTimeToDateTime(const SystemTime: TSystemTime):TDateTime; Converts system time to datetime 39 function TimeStampToDateTime(const TimeStamp: TTimeStamp):TDateTime; Converts time stamp to DateTime 40 function TimeStampToMSecs(const TimeStamp: TTimeStamp):comp; Converts Timestamp to number of milliseconds 41 function TimeToStr(Time: TDateTime):; Returns string representation of Time 42 function TimeToStr(Time: TDateTime; const FormatSettings: TFormatSettings):; Returns string representation of Time 43 function Time: TDateTime; Get current time The following example illustrates the use of some of the above functions − dpkg -i fpc-XXX.deb 57 When the above code was compiled and executed, it produced the following result: dpkg -i fpc-XXX.deb 58 Pascal - Object OrientedWe can imagine our universe made of different objects like sun, earth, moon, etc. Similarly, we can imagine our car made of different objects like wheel, steering, gear, etc. Same way, there are object-oriented programming concepts, which assume everything as an object and implement a software using different objects. In Pascal, there are two structural data types used to implement a real world object −
Object-Oriented ConceptsBefore we go in detail, let's define important Pascal terms related to Object-Oriented Pascal.
Defining Pascal ObjectsAn object is declared using the type declaration. The general form of an object declaration is as follows − dpkg -i fpc-XXX.deb 59 Let us define a Rectangle Object that has two integer type data members - length and width and some member functions to manipulate these data members and a procedure to draw the rectangle. dpkg -i fpc-XXX.deb 60 After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only. Following example shows how to set lengths and widths for two rectangle objects and draw them by calling the member functions. dpkg -i fpc-XXX.deb 61 Following is a complete example to show how to use objects in Pascal − dpkg -i fpc-XXX.deb 62 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 63 Visibility of the Object MembersVisibility indicates the accessibility of the object members. Pascal object members have three types of visibility − Sr.No Visibility & Accessibility 1 Public The members can be used by other units outside the program unit 2 Private The members are only accessible in the current unit. 3 Protected The members are available only to objects descended from the parent object. By default, fields and methods of an object are public and are exported outside the current unit. Constructors and Destructors for Pascal Objects −Constructors are special type of methods, which are called automatically whenever an object is created. You create a constructor in Pascal just by declaring a method with a keyword constructor. Conventionally, the method name is Init, however, you can provide any valid identifier of your own. You can pass as many arguments as you like into the constructor function. Destructors are methods that are called during the destruction of the object. The destructor methods destroy any memory allocation created by constructors. Following example will provide a constructor and a destructor for the Rectangle class which will initialize length and width for the rectangle at the time of object creation and destroy it when it goes out of scope. dpkg -i fpc-XXX.deb 64 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 65 Inheritance for Pascal ObjectsPascal objects can optionally inherit from a parent object. The following program illustrates inheritance in Pascal Objects. Let us create another object named TableTop, which is inheriting from the Rectangle object. dpkg -i fpc-XXX.deb 66 Following are the important points which should be noted down −
When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 67 Pascal - ClassesYou have seen that Pascal Objects exhibit some characteristics of object-oriented paradigm. They implement encapsulation, data hiding and inheritance, but they also have limitations. For example, Pascal Objects do not take part in polymorphism. So classes are widely used to implement proper object-oriented behavior in a program, especially the GUI-based software. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack. In other words, when you declare a variable the object type, it will take up as much space on the stack as the size of the object, but when you declare a variable of the class type, it will always take the size of a pointer on the stack. The actual class data will be on the heap. Defining Pascal ClassesA class is declared in the same way as an object, using the type declaration. The general form of a class declaration is as follows − dpkg -i fpc-XXX.deb 68 Its worth to note following important points −
Let us define a Rectangle class that has two integer type data members - length and width and some member functions to manipulate these data members and a procedure to draw the rectangle. dpkg -i fpc-XXX.deb 69 Let us write a complete program that would create an instance of a rectangle class and draw the rectangle. This is the same example we used while discussing Pascal Objects. You will find both programs are almost same, with the following exceptions −
Here is the complete example − dpkg -i fpc-XXX.deb 70 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 71 Visibility of the Class MembersVisibility indicates the accessibility of the class members. Pascal class members have five types of visibility − Sr.No Visibility & Accessibility 1 Public These members are always accessible. 2 Private These members can only be accessed in the module or unit that contains the class definition. They can be accessed from inside the class methods or from outside them. 3 Strict Private These members can only be accessed from methods of the class itself. Other classes or descendent classes in the same unit cannot access them. 4 Protected This is same as private, except, these members are accessible to descendent types, even if they are implemented in other modules. 5 Published This is same as a Public, but the compiler generates type information that is needed for automatic streaming of these classes if the compiler is in the {$M+} state. Fields defined in a published section must be of class type. Constructors and Destructors for Pascal ClassesConstructors are special methods, which are called automatically whenever an object is created. So we take full advantage of this behavior by initializing many things through constructor functions. Pascal provides a special function called create() to define a constructor. You can pass as many arguments as you like into the constructor function. Following example will create one constructor for a class named Books and it will initialize price and title for the book at the time of object creation. dpkg -i fpc-XXX.deb 72 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 73 Like the implicit constructor named create, there is also an implicit destructor method destroy using which you can release all the resources used in the class. InheritancePascal class definitions can optionally inherit from a parent class definition. The syntax is as follows − dpkg -i fpc-XXX.deb 74 Following example provides a novels class, which inherits the Books class and adds more functionality based on the requirement. dpkg -i fpc-XXX.deb 75 When the above code is compiled and executed, it produces the following result − dpkg -i fpc-XXX.deb 76 Its worth to note following important points −
InterfacesInterfaces are defined to provide a common function name to the implementers. Different implementers can implement those interfaces according to their requirements. You can say, interfaces are skeletons, which are implemented by developers. Following is an example of interface − dpkg -i fpc-XXX.deb 77 Please note that, when a class implements an interface, it should implement all methods of the interface. If a method of an interface is not implemented, then the compiler will give an error. Abstract ClassesAn abstract class is one that cannot be instantiated, only inherited. An abstract class is specified by including the word symbol abstract in the class definition, like this − dpkg -i fpc-XXX.deb 78 When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibility. Static KeywordDeclaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static cannot be accessed with an instantiated class object (though a static method can). The following example illustrates the concept − |