Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Pascal (programming language)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Language constructs== Pascal, in its original form, is a purely [[procedural language]] and includes the traditional array of [[ALGOL]]-like control structures with reserved words such as <code>if</code>, <code>then</code>, <code>else</code>, <code>while</code>, <code>for</code>, and <code>case</code>, ranging on a single statement or a <code>begin</code>-<code>end</code> statements block. Pascal also has data structuring constructs not included in the original [[ALGOL 60]] [[type system|types]], like [[Record (computer science)|record]]s, variants, [[pointer (computer programming)|pointer]]s, [[enumerated type|enumeration]]s, and [[set (computer science)|set]]s and procedure pointers. Such constructs were in part inherited or inspired from [[Simula]] 67, [[ALGOL 68]], [[Niklaus Wirth]]'s own [[ALGOL W]] and suggestions by [[C. A. R. Hoare]]. Pascal programs start with the <code>program</code> [[keyword (computer programming)|keyword]] with a list of external [[file descriptor]]s as parameters<ref name="iso/iec 7185:1990 6.10">[http://www.moorecad.com/standardpascal/iso7185.pdf Pascal ISO 7185:1990] {{webarchive|url=https://web.archive.org/web/20120617105237/http://www.moorecad.com/standardpascal/iso7185.pdf |date=2012-06-17}} 6.10</ref> (not required in Turbo Pascal etc.); then follows the main [[block (programming)|block]] bracketed by the <code>begin</code> and <code>end</code> keywords. [[Semicolon]]s separate [[Statement (programming)|statements]], and the [[full stop]] (i.e., a period) ends the whole program (or ''unit''). [[Letter case]] is ignored in Pascal source. Here is an example of the source code in use for a very simple [["Hello, World!" program]]: :<syntaxhighlight lang="pascal"> program HelloWorld(output); begin WriteLn('Hello, World!') {No ";" is required after the last statement of a block - adding one adds a "null statement" to the program, which is ignored by the compiler.} end. </syntaxhighlight> ===Data types=== A Type Declaration in Pascal is used to define a range of values which a variable of that type is capable of storing. It also defines a set of operations that are permissible to be performed on variables of that type. The predefined types are: {| class="wikitable" |- ! Data type ! Type of values which the variable is capable of storing |- | [[integer (computer science)|integer]] | integer (whole) numbers |- | [[floating-point arithmetic|real]] | floating-point numbers |- | [[Boolean type|Boolean]] | the values True or False |- | [[character (computing)|char]] | a single character from an ordered character set |- | [[set (computer science)|set]] | equivalent to an array of [[Boolean type|Boolean]] values |- | [[Array data type|array]] | a countable group of any of the preceding data types, of records, or of other arrays |- | [[Record (computer science)|record]] | A collection of any of the preceding data types or of other records |- | [[string (computer science)|string]] | a sequence or "string" of characters is declared as a "packed array of char" with a starting index of 1. These can be assigned string constants and individual characters can be accessed as elements of the array. |} The range of values allowed for the basic types (except Boolean) is implementation defined. Functions are provided for some data conversions. For conversion of <code>real</code> to <code>integer</code>, the following functions are available: <code>round</code> (using [[Rounding#Rounding_half_away_from_zero|rounding half away from zero]]) and <code>trunc</code> (rounds towards zero). The programmer has the freedom to define other commonly used data types (e.g. byte, string, etc.) in terms of the predefined types using Pascal's type declaration facility, for example :<syntaxhighlight lang="pascal"> type byte = 0..255; signed_byte = -128..127; string = packed array[1..255] of char; </syntaxhighlight> Often-used types like byte and string are already defined in many implementations. Normally the system will use a [[Word (computer architecture)|word]] to store the data. For instance, the {{code|byte}} type may be stored in a machine integer - 32 bits perhaps - rather than an [[8-bit computing|8-bit]] value. Pascal does not contain language elements that allow the basic storage types to be defined more granularly. This capability was included in a number of Pascal extensions and follow-on languages, while others, like [[Modula-2]], expanded the built-in set to cover most machine data types like 16-bit integers. The {{code|packed}} keyword tells the compiler to use the most efficient method of storage for the structured data types: sets, arrays and records, rather than using one [[Word (computer architecture)|word]] for each element. Packing may slow access on machines that do not offer easy access to parts of a word. ===Subrange types=== Subranges of any [[ordinal data type]] (any simple type except real) can also be made: :<syntaxhighlight lang="pascal"> var x : 1..10; y : 'a'..'z'; </syntaxhighlight> ===Set types=== In contrast with other programming languages from its time, Pascal supports a set type:<ref name="Mandell1987">{{cite book |first=Steven L. |last=Mandell |title=Pascal Programming Today |url=https://archive.org/details/turbopascalprogr00mand |url-access=registration |year=1987 |publisher=West Publishing Company |isbn=978-0-314-33935-5}}</ref> :<syntaxhighlight lang="pascal"> var Set1 : set of 1..10; Set2 : set of 'a'..'z'; </syntaxhighlight> A set is a fundamental concept for modern mathematics, and they may be used in many algorithms. Such a feature is useful and may be faster than an equivalent construct in a language that does not support sets. For example, for many Pascal compilers: :<syntaxhighlight lang="pascal"> if i in [5..10] then ... </syntaxhighlight> executes faster than: :<syntaxhighlight lang="pascal"> if (i > 4) and (i < 11) then ... </syntaxhighlight> Sets of non-contiguous values can be particularly useful, in terms of both performance and readability: :<syntaxhighlight lang="pascal"> if i in [0..3, 7, 9, 12..15] then ... </syntaxhighlight> For these examples, which involve sets over small domains, the improved performance is usually achieved by the compiler representing set variables as [[bit vector]]s. The set [[Operator (programming)|operators]] can then be implemented efficiently as bitwise machine code operations. ===Record types=== An example of a Pascal record type: :<syntaxhighlight lang="pascal"> type car = record length: integer; width: integer end; </syntaxhighlight> An example of a variant record type: :<syntaxhighlight lang="pascal"> type Shape = (Circle, Square, Triangle); Dimensions = record case Figure: Shape of Circle: (Diameter: real); Square: (Width: real); Triangle: (Side: real; Angle1, Angle2: 0..360) end; </syntaxhighlight> Variant records allow several fields of the record to overlap each other to save space. ===Type declarations=== Types can be defined from other types using type declarations: :<syntaxhighlight lang="pascal"> type x = integer; y = x; ... </syntaxhighlight> Further, complex types can be constructed from simple types: :<syntaxhighlight lang="pascal"> type a = array[1..10] of integer; b = record x : integer; y : char {extra semicolon not strictly required} end; c = file of a; </syntaxhighlight> Further, complex types can be constructed from other complex types recursively: :<syntaxhighlight lang="pascal"> const Jack = 11; Queen = 12; King = 13; Ace = 14; type valueType = 2..Ace; suitType = club, diamond, heart, spade; cardType = record suit: suitType; value: valueType; end; deckType = array [1..52] of cardType; person = record surname: packed array [1..20] of char; age: integer; end; table = record hands: array [1..3] of deckType; players: array [1..4] of person; end; </syntaxhighlight> ===File type=== :<syntaxhighlight lang="pascal"> type a = file of integer; b = record x : integer; y : char end; c = file of b; </syntaxhighlight> As shown in the example above, Pascal [[Computer file|files]] are sequences of components. Every file has a buffer variable which is denoted by ''f^''. The procedures ''get'' (for reading) and ''put'' (for writing) move the buffer variable to the next element. Read is introduced such that ''read(f, x)'' is the same as ''x := f^; get(f);''. Write is introduced such that ''write(f, x)'' is the same as ''f^ := x; put(f);'' The type {{code|text}} is predefined as file of char. While the buffer variable could be used for inspecting the next character to be used (check for a digit before reading an integer), this leads to serious problems with interactive programs in early implementations, but was solved later with the "lazy I/O" concept, which waits until the file buffer variable is actually accessed before performing file operations. ===Pointer types=== Pascal supports the use of [[pointer (computer programming)|pointer]]s: :<syntaxhighlight lang="pascal"> type pNode = ^Node; Node = record a : integer; b : char; c : pNode end; var NodePtr : pNode; IntPtr : ^integer; </syntaxhighlight> Here the variable ''NodePtr'' is a pointer to the data type ''Node'', a record. Pointers can be used before they are declared. This is a [[forward declaration]], an exception to the rule that things must be declared before they are used. To create a new record and assign the value ''10'' and character ''A'' to the fields ''a'' and ''b'' in the record, and to initialise the pointer ''c'' to the [[null pointer]] ("NIL" in Pascal), the statements would be: :<syntaxhighlight lang="pascal"> new(NodePtr); ... NodePtr^.a := 10; NodePtr^.b := 'A'; NodePtr^.c := nil; ... </syntaxhighlight> This could also be done using the <code>with</code> statement, as follows: <syntaxhighlight lang="pascal"> new(NodePtr); ... with NodePtr^ do begin a := 10; b := 'A'; c := nil end; ... </syntaxhighlight> Inside of the scope of the ''with'' statement, a and b refer to the subfields of the record pointer ''NodePtr'' and not to the record Node or the pointer type pNode. [[Linked list]]s, [[Stack (abstract data type)|stacks]] and [[Queue (abstract data type)|queues]] can be created by including a pointer type field (c) in the record. Unlike many languages that feature pointers, Pascal only allows pointers to reference dynamically created variables that are anonymous, and does not allow them to reference standard static or local variables. Pointers also must have an associated type, and a pointer to one type is not compatible with a pointer to another type (e.g. a pointer to a char is not compatible with a pointer to an integer). This helps eliminate the type security issues inherent with other pointer implementations, particularly those used for [[PL/I]] or [[C (Programming Language)|C]]. It also removes some risks caused by [[dangling pointers]], but the ability to dynamically deallocate referenced space by using the ''dispose'' function (which has the same effect as the ''free'' library function found in [[C (programming language)|C]]) means that the risk of dangling pointers has not been eliminated<ref name="Hoare.Sneeringer.Welsh.1977">J. Welsh, W. J. Sneeringer, and C. A. R. Hoare, "Ambiguities and Insecurities in Pascal", ''Software: Practice and Experience 7'', pp. 685β696 (1977)</ref> as it has in languages such as Java and C#, which provide [[Garbage collection (computer science)|automatic garbage collection]] (but which do not eliminate the related problem of [[memory leak]]s). Some of these restrictions can be lifted in newer dialects. ===Control structures=== Pascal is a [[structured programming]] language, meaning that the flow of control is structured into standard [[Statement (programming)|statements]], usually without '[[goto (command)|goto]]' commands. :<syntaxhighlight lang="pascal"> while a <> b do WriteLn('Waiting'); if a > b then WriteLn('Condition met') {no semicolon allowed before else} else WriteLn('Condition not met'); for i := 1 to 10 do {no semicolon here as it would detach the next statement} WriteLn('Iteration: ', i); repeat a := a + 1 until a = 10; case i of 0 : Write('zero'); 1 : Write('one'); 2 : Write('two'); 3,4,5,6,7,8,9,10: Write('?') end; </syntaxhighlight> ===Procedures and functions=== Pascal structures programs into procedures and functions. Generally, a procedure is used for its side effects, whereas a function is used for its return value. :<syntaxhighlight lang="pascal"> program Printing(output); var i : integer; procedure PrintAnInteger(j : integer); begin ... end; function triple(x: integer): integer; begin triple := x * 3 end; begin { main program } ... PrintAnInteger(i); PrintAnInteger(triple(i)) end. </syntaxhighlight> Procedures and functions can be nested to any depth, and the 'program' construct is the logical outermost block. By default, parameters are passed by value. If 'var' precedes a parameter's name, it is passed by reference. Each procedure or function can have its own declarations of goto labels, constants, types, variables, and other procedures and functions, which must all be in that order. This ordering requirement was originally intended to allow efficient [[single-pass compilation]]. However, in some dialects (such as [[Delphi (software)|Delphi]]) the strict ordering requirement of declaration sections has been relaxed. ===Semicolons as statement separators=== Pascal adopted many language syntax features from the [[ALGOL]] language, including the use of a semicolon as a statement separator. This is in contrast to other languages, such as [[PL/I]] and [[C (programming language)|C]], which use the semicolon as a statement terminator. No semicolon is needed before the <code>end</code> keyword of a record type declaration, a block, or a ''case'' statement; before the <code>until</code> keyword of a repeat statement; and before the <code>else</code> keyword of an ''if'' statement. The presence of an extra semicolon was not permitted in early versions of Pascal. However, the addition of [[ALGOL]]-like empty statements in the 1973 ''Revised Report'' and later changes to the language in ISO 7185:1983 now allow for optional semicolons in most of these cases. A semicolon is still not permitted immediately before the <code>else</code> keyword in an ''if'' statement, because the <code>else</code> follows a single statement, not a statement sequence. In the case of nested ifs, a semicolon cannot be used to avoid the [[dangling else]] problem (where the inner if does not have an else, but the outer if does) by putatively terminating the nested if with a semicolon β this instead terminates both if clauses. Instead, an explicit <code>begin</code>...<code>end</code> block must be used.<ref>''Pascal,'' Nell Dale and Chip Weems, "Dangling Else", [https://books.google.com/books?id=5x2k4vWwn1wC&pg=PA160 p. 160β161] {{webarchive|url=https://web.archive.org/web/20170318223956/https://books.google.com/books?id=5x2k4vWwn1wC&pg=PA160 |date=2017-03-18}}</ref>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)