Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Pascal Programming/Variables and Constants

From Wikibooks, open books for an open world
<Pascal Programming

Like all programming languages, Pascal provides some means to modify memory.This concept is known as variables.Variables are named chunks of memory.You can use them to store data you cannot predict.

Constants, on the other hand, are named pieces of data.Youcannot alter them during run-time, but they arehard-coded into the compiled executable program.Constants do not necessarily occupy any dedicated unique space in memory, but facilitate writing clean and understandable source code.

Declaration

[edit |edit source]

In Pascal, before you are even allowed to useany variable or constant you have to declare them, like virtually any symbol in Pascal.A declaration makes a certain symbolknown to the compiler and possibly instructs it to make the necessary provisions for their effective usage, that means – in the context of variables – earmark some piece of memory.

A declaration is always a two-tuple(identifier,definition){\displaystyle \left({\text{identifier}},{\text{definition}}\right)}, to be more specific, variables are declared like(identifier,data type){\displaystyle \left({\text{identifier}},{\text{data type}}\right)} and constant declarations are(identifier,literal){\displaystyle \left({\text{identifier}},{\text{literal}}\right)} tuples.A tuple is anordered collection.You may not reverse or rearrange its items without the tuple rendering to bedifferent.

NoteAfter you have declared an identifier to refer to one thing, you may not re-declare the same identifier to refer to another (or same) thing (“shadowing” may apply, but more on that later).

Identifiers

[edit |edit source]

Structure

[edit |edit source]

Identifiers are names denoting constants, types, bounds, variables, procedures, and functions.They must begin with a letter, which may be followed by any combination and numbers of letters and digits.The spelling of an identifier is significant over its whole length.Corresponding upper-case and lower-case letters are considered equivalent.[1]

Letters refers to the modern Latin alphabet, that is all letters you use in writing English words, anddigits are Western Arabic digits.

Usage

[edit |edit source]

As you infer from the quote’s last sentence, the casing of letters does not matter:Foo andfOO are both thesame identifier, just different representations.

Identifiers are used simply by writing them out at a suitable position.

Significant characters

[edit |edit source]

In the age Pascal was developed in, computer memory was a precious resource.In order to build a working compiler, however, the notion ofsignificant characters was introduced.A significant character of an identifier is a character that contributes to distinguishing two identifiers from one another.

Some programming languages had a limit of 8 (eight) characters.This led to very cryptic identifiers.Today, however, the limit of significant characters is primarily governed by usability:The programmer eventually has to type them out if noIDE supports some auto-completion mechanism.TheFPC, for example, has a limit of 127 characters:

Identifiers consist of between1 and127 significant characters (letters, digits and the underscore character), of which the first must be a letter (az orAZ), or an underscore (_).[2]

NoteYou are still allowed to write identifierslonger than 127 characters, however, the compiler only looks at the first 127 characters and discards the remaining characters as irrelevant.

Note, allowing_, too, is an ISO 10206 (“Extended Pascal”) extension, but – unlike theFPC – it imposes the restriction that an identifier may neither begin or end an identifier, nor may two underscores appear one another.

Variables

[edit |edit source]

Variable section

[edit |edit source]

Variables are declared in a dedicated section, thevar-section.

programvarDemo(input,output);varnumber:integer;beginwrite('Enter a number: ');readLn(number);writeLn('Great choice! ',number,' is awesome.');end.

When the compiler processes thevar-section it will set as much memory aside as is required by its associated data type.Here, we instruct the compiler to reserve space for aninteger.Aninteger is a data type that is part of the programming language, thus it is guaranteed to be present regardless of the used compiler.It stores a subset of ℤ, the set of integers, like for example42,1337 or-1.

Data type

[edit |edit source]

Data type refers to the combination of a permissible range of values and permissible operations on this range of values.Pascal defines some basic data types as part of the language.Apart frominteger there are also:

char
A character, like a Latin letter or Western Arabic digit, but also spaces and other characters.
real
A subset of ℚ, that is – due to computer’s binary nature – the set of rational numbers. Examples are0.015625 (2−6) or73728.5 (216 + 213 + 2−1).
Boolean
A Boolean value, that isfalse ortrue.

Each data type defines how data are laid out in memory.In a high-level language, such as Pascal, it is not of the programmer’s concern how exactly the data are stored, but the processor (i. e. in most cases a compiler) has to define it.

We will revisit all data types later on.

Reading from the console

[edit |edit source]

As you may have noticed, the example above containsreadLn(number) and the program header also listsinput.ReadLn will (try to) read data from the (optionally named) source and store the (interpreted) values into the supplied parameters discarding any line-end characters.If the source is not specified, like it is the case here,input is assumed, thusreadLn(number) is equivalent toreadLn(input, number), but shorter.

When the program is run, it will stop and wait for the user to input a number, that is a literal that can be converted into the argument’s data type.

If you do not enter a literal that is compatible to the type of the supplied argument, something like this happens:
Enter a number: I want cookies!./a.out: sign or digit expected (error #552 at 402ac3)
And then the program aborted. The followingwriteLn was not executed. Now obviouslyI want cookies! is not a literal that can be converted into aninteger value (i. e. the data type ofnumber). For reference, this error message was generated with the program compiled using theGPC. Programs compiled with different compilers may emit different error messages.

You have to indicate in your program’s accompanying documents – the user manual – how and when the user needs to input data.Later we will learn how to treat erroneous input, but this is too complex for now.

More variables

[edit |edit source]

There can be as manyvar-sections as necessary, but they may not be empty.There is also a shorthand syntax for declaring many variables of thesame type:

varfoo,bar,x:integer;

This will declarethree independent variables, all of theinteger data type.Nonetheless,different types have to appear in different declarations:

varx:integer;itIsSunnyInPhiladelphia:Boolean;

Constants

[edit |edit source]

Constant section

[edit |edit source]
programconstDemo(output);constanswer=42;beginwriteLn('The answer to the Ultimate Question of ','Life, the Universe, and Everything, is: ',answer);end.

Usage

[edit |edit source]

As already mentioned in the introduction, a constant may never change its value, but you have to modify the source code.Consequently, the name of a constant cannot appear on the left-hand side of an assignment.

Pre‑defined constants

[edit |edit source]

There are some already predefined constants:

maxInt
This is the maximuminteger value aninteger variable could assume. There is nominimum integer constant, but it is guaranteed that ainteger variable can at least store the value-maxInt.
maxChar
Likewise, this is the maximumchar value achar variable could assume, wheremaximum refers to the ordinal value using the built-inord function.
maxReal,minReal andepsReal
Are defined by the “Extended Pascal” standard.
false andtrue
Refer to Boolean values.

Rationale

[edit |edit source]

Pascal was designed, so – among other considerations – it could be compiled in one pass, from top to bottom:The reason being to make compiling fast and simple.Distinguishing between variables and constants allows the processor to simply substitute any occurrence of a constant identifier to be replaced by its value.Thus, a constant does not need any special treatment like a variable, yet allows the programmer to reuse reappearing data.

Tasks

[edit |edit source]
Does the German wordZähler (meaning “counter” / “enumerator”) constitute a valid identifier?
No, because the letter Umlaut-a (ä) is not a letter in the English alphabet. Identifiers may only consist of (English alphabet) letters and (Western Arabic) digits. As a word of advice, stick to English words as identifiers even though your native language is a different one.
No, because the letter Umlaut-a (ä) is not a letter in the English alphabet. Identifiers may only consist of (English alphabet) letters and (Western Arabic) digits. As a word of advice, stick to English words as identifiers even though your native language is a different one.


Is1direction (1D) a permissible identifier?
This is also not a valid identifier. All identifiers have to start with a letter. This restriction allows compiler vendors to assume, once a digit is encountered, that a number literal follows.
This is also not a valid identifier. All identifiers have to start with a letter. This restriction allows compiler vendors to assume, once a digit is encountered, that a number literal follows.


What is the difference betweenwrite andwriteLn?
They are the same except that, as the name already indicates,writeLn puts the cursor into the next line after it has printed all its parameters.
They are the same except that, as the name already indicates,writeLn puts the cursor into the next line after it has printed all its parameters.


References:

  1. Jensen, Kathleen; Wirth, Niklaus.Pascal – user manual and report (4th revised ed.).doi:10.1007/978-1-4612-4450-9.ISBN 978-0-387-97649-5.{{cite book}}:no-break space character in|title= at position 7 (help)
  2. Michaël Van Canneyt (September 2017). "§1.4". Free Pascal Reference guide. version 3.0.4. p. 15. ftp://ftp.freepascal.org/pub/fpc/docs-pdf/ref.pdf. Retrieved 2019-12-14. 


Next Page: Input and Output | Previous Page: Beginning
Home: Pascal Programming
Retrieved from "https://en.wikibooks.org/w/index.php?title=Pascal_Programming/Variables_and_Constants&oldid=4442582"
Category:
Hidden category:

[8]ページ先頭

©2009-2025 Movatter.jp