Why Pascal Is Not My Favorite Programming Language

zhaozj2021-02-16  49

AT & T Bell Laboratories Murray Hill, New Jersey 07974

Computing Science Technical Report No. 100

Why Pascal Is Not My Favorite Programming Language

Brian W. Kernighan

April 2, 1981

Why Pascal Is Not My Favorite Programming Language

Brian W. Kernighan

AT & T Bell Laboratories Murray Hill, New Jersey 07974

Abstract

The Programming Language Pascal Has Become THE DOMINANT LANGUAGE OF

IT HAS Also Strongly Influenced. IT HAS Also Strongly Influenced

Lan Guages ​​Developed Subsequently, in Particular Ada.

Pascal Was Originally Intended Primarily As a Teaching Language, But It HAS

Been more and more often recommended as a language for Serious Programming As

Well, for Example, for System Programming Tasks and Even Operating Systems.

Pascal, At Least In Its Standard Form, IS Just Plain Not Suitable for Serious

Pro gramming. This paper discusses my personal discovery of some of the

Reasons why.

April 2, 1981

Why Pascal Is Not My Favorite Programming Language

Brian W. Kernighan

AT & T Bell Laboratories Murray Hill, New Jersey 07974

Genesis

This Paper Has Its Origins in Two Events - a Spate of Papers That Compare C

And Pas Cal 1, 2, 3, 4 And a Personal Attempt To Rewrite Software Tools 5 in

Pascal.

Comparing c and pascal is rather like committed a learjet to a piper cub -

One Is Meant for getting Something Done While The Other Is Meant for Learning

- So Such Comparisons Tend to Be Somewhat Farfetched. But The Revision of

Software Tools Seems A More Relevant Comparison. The Programs Therein WERE

Originally Written in Ratfor, A `` Structured '' Dialect Of Fortran IMPLE MENTED

By a Preprocessor. Since Ratfor Is Really Fortran in Disguise, IT Has Few of

THE Assets That Pascal Brings - Data Types More Suited To CharacterProcessing, Data Structuring Capabilities for Better Defining The Organization

Of One's Data, And Strong Typing to Enforce Telling The Truth About The Data.

IT Turned Out To Be Harden Tan I Had Expected to Rewrite The Programs in

Pascal. This paper is an attempt to distill out of the experience some

Lessons About Pascal's Suitability for Program Ming (as distinguished from

Learning About Programming). IT IS Not a Comparison of Pascal with C OR

Ratfor.

The Programs Were First Written in That Diaract of Pascal Supported by The Dialect Of Pascal Supported by THE

Pascal Interpreter Pi Provided by the University of California at Berkeley.

THE LANGUAGE IS Close To The Nominal Standard of Jensen and Wirth, 6 with good

Diagnostics and Careful Run-Time Checking. Since The Programs Have ALSO

Been Run, Unchanged Except for New Libraries of Primitives, on Four Other

Systems: an interpreter from the free university of amsterdam (hereinafter

Referred to as vu, for vrije universiteit, a VAX Version of the Berkeley

System (a true compiler), a compiler purveyed by Whitesmiths, Ltd., and ucsd

Pascal on a z80. All but the last of these pascal systems arewritten in C.

Pascal IS a MUCH-Discussed Language. A Recent Bibliography 7 Lists 175 Items

Under the Heading of `` Discussion, Analysis and Debate. '' the Most OFTEN

Cited Papers (Well Worth Reading Are A Strong Critique by Habermann 8 and An AN

Equally strong rejointer by lecarme and des jardins. 9 the paper by boom and

Dejong 10 is Also Good Reading. Wirth's OWN Assessment of Pas Cal is Found in

[11]. I have no desire or ability to summarize the literature; this paper

Represents My Personal Observations and MOST OF IT Necessarily DuplicateSpoints Made by Others.

Around the issues of

Types and Scope Control Flow Environment Cosmetics

And thein Each Area More Or Less in Decreasing ORDER OF SIGNIFICANCE.

To State My Conclusions At The Outset: Pascal May Be An Admirable Language for

TEACHING BEGINNERS HOW TO Program; i Have No First-hand Experience with That.

IT Was a ConsideRable Achievement for 1968. It Has Certainly Influenced The

Design of Recent Languages, of Which ada is likely to be the max important.

But in Its Standard Form (Both Current and Proposed), Pascal Is Not Adequate

For Writing Real Programs. It is suitable only for small, self-contained

Programs That Have ONLY TRIVIAL INTERACITIONS with THEIR ENVIRONMENT AND THAT

Make no use of any slowware Written by Anyone else.

2. Types and scopes

Pascal IS (Almost) a strongly typed language. Roughly Speaking, That Means

That Each Object In a Program Has A Well-Defined Type Which Implicitly Defines

The Legal Values ​​of and Operations on The Object. The Language Guarantees

That It Will Prohibit Illegal Values ​​and Operations, by Some MixTure Of

Compile- and run-time checking. of course compilers May Not Actually Do All

THE CHECKING IMPLIED in The language definition. furthermore, Strong Typing

Is Not to Be Confused With Dimensional Analysis. if one defines types apple

And Orange With

Type apple = integer; orange = integer;

THEN Any Arbitrary Arithmetic Expression Involving Apples and Oranges IS

Perfectly legal.

Strong Typing Shows Up in a variety of ways. For instance, arguments to

Functions and pro CEDURES Are Checked for Proper Type Matching. gone is thefort doms to pass A Floating Point Number INTO A SUBROTINE THATS EXPECTS

AN Integer; this I deem A Desirable Attribute of Pascal, Since It Warns of A

Construction That Will Certainly Cause An Error.

Integer Variables May Be Declared to Have An Associated Range of LEGAL VALUES,

And the CoM Piler and Run-Time Support Ensure That Does Not Put Large

Integers INTO VARIABLES That Only Hold Small Ones. THIS TOO Seem Like A

Service, Although Of Course Run-Time Checking Does Exact a Penalty.

Let us move on to some problems of type and scpe.

2.1. The size of an array is part of its type

IF One Declares

Var Arr10: array [1..10] of integer; arR20: array [1..20] of integer;

THEN ARR10 and ARR20 Are Arrays of 10 and 20 Integers Respectively. suppose

We want to write a procedure sort to sort an integer array. because arr10 and

Arr20 Have Different Types, IT IS Not Possible To Write A Single Procedure

That Will Sort Them Both.

The Place WHERE this Affects Software Tools Particularly, And i think Programs

In General, Is That It Makes It Difficult Indeed To Create A Library of

Routines for doing commit, general-purpose operations like sorting.

The Particular Data Type Most often Affected Is Array of Char, for in Pascal A

String is an array of character, consider Writing a Function Index (S, C) That

Will Return The Position in The String S Where The Character C First Occurs,

Or Zero if it does not. The problem is how to handle the string argument of

Index. The Calls Index ('Hello', c) And Index ('Goodbye', C) Can Not Both Be

Legal, Since The Strings Have Different Lengths. (i Pass over The Question of

How the end of a constant string like 'Hello' Can Be Detected, Because Itcan't.)

The next Try IS

Var Temp: array [1..10] of char;

Temp: = 'hello';

N: = index (TEMP, C);

But The Assignment to Temp is Illegal Because 'Hello' and Temp Aref

DiffERENT Length.

The only escape from this infinite regress is to define a family of routines

With a member for each possible string size, or to make all strings (including

Constant strings like 'define') of The Same Length.

The Latter Approach Is The Leesr of Two Great Evils. In Tools, a Type Called

String is declared as

TYPE STRING = array [1..maxstr] of char;

WHERE The Constant MaxStr Is `` Big Enough, '' and all strings in all programs

Are EXACTLY THISE. THIS FAR from Ideal, Although It Made It Possible To

Get The Programs Running. It Does NOT SOLVE The Problem of Creating True

Libraries of useful routines.

There Are Some Situations Where It Is Simply Not Acceptable To Use To

Fixed-Size Array Repre Sentation. for Example, The Tools Program To Sort

Lines of text operates by Filling Up Memory with as a list; as a will fit;

ITS Running Time Depends Strongly On How Full The Memory Can Be Packed. Thus

For Sort, ANOTHER REPRESENTATION IS Used, a long Array of Characters and A Set

Of INDES INTO this Array:

TYPE Charbuf = array [1..maxbuf] of char; charIndex = array [1..maxindex] of

0..maxbuf;

But The Procedures and Functions Written To Process The Fixed-Length

Representation cannot be used with the variable-length form; an entirely new

Set of routines is needed to copy and com pare strings in this representation.

In Fortran or C The Same Functions Could Be Used for Both.

As Suggested Above, a constant string is whitten as'this is a string '

And Has The Type Packed Array [1..n] of char, where n is the length. thus

Each String Literal of Different Length Has A Different Type. The Only Way To

Write a Routine That Will Print A Message and Clean Up Is To Pad All Messages

Out to the Same Maximum Length:

Error ('Short Message'); Error ('this is a homewhat longer message ";

Many Commercial Pascal Compilers Provide A String Data Type That Explicitly

Avoids The Problem; String's Are All Taken to Be The Same Type Regardless of

Size. This Solves The Problem for this Single Data Type, But no Other. IT

Also Fails To Solve Secondary Problems Like Computing The Length of a constant

String; Another Built-in Function is The Usual Solution.

Pascal Enthusiasts Offen Claim That To Cope with The Array-Size Problem ONE

MRELY HAS TO COPY SOME LIBRARY ROUTINE AND FILL in the parameters for the

Program At Hand, But The Defense Sounds Weak At Best: 12

`` Since The Bounds of An Array Are Part of Its Type (OR, More Exactly, of The

TYPE OF ITS INDEXES, IT IS IMPOSSIBLE TO Define A Procedure or Function Which

Applies to Arrays with Differge Bounds. Althought this Restriction May Appear

To be a severe one, The Experiences We Have Had with Pascal Tend To show That

IT TENDS TO OCCUR VERY INFRE QUENTLY. [...] ho weever, the need to bind the

Size of parametric arrays is a serious defect in connection with the use of

Program libraries. ''

This Botch is The Biggest Single Problem with Pascal. I Believe That if IT

Could Be Fixed, The Language Would Be An ORDER OF MAGNITUDE More Use. The

Proposed Iso Standard for Pascal 13

Provides Such A Fix (`` Conformant Array Schemas'), But The Acceptance of Thispart of The Standard is Apparently Still in Doubt.

2.2. There Are no static variables and no initialization

A static variable (offen called an own variable in algol-speaking country)

Is One That Is Pri Vate To Some Routine And Retains Its Value from One Call of

The routine to the next. de Facto, for Tran Variables Are INTERNAL STATIC,

Except for common; # in c there is a static declaration That Can Be Applied To

Local variables. __________________

# Strictly speaking, in Fortran 77 One Must Use save to force the static

Attribute.

Pascal Has No Such Storage Class. This Means That IF A Pascal Function OR

Procedure Intends to Remember a Value from One Call to Another, The Variable

Used Must Be External To The Function or Procedure. Thus it Must Be visible

TO Other Procedures, And ITS Name Must Be Unique In The Larger Scope. a

SIMPLE EXAMPLE OF THE PROBLEM IS A Random Number Generator: The Value Used To

Compute the capital output must be saved to compute the next one, so it must

Be stores in a vari able whose lifetime incrudes all calls of the random

Number Generator. in Practice, this is type in u outermost block of there

Program. thus the declaration of selfh a variable is far remoded from the

Place where it is actually used.

One Example Comes from The Text Formatter Described in Chapter 7 of Tools. The THE

Variable Dir Controls The Direction from Which Excess Blanks Are Inserted

During Line Justification, TO Obtain Left and Right Alternately, in Pascal,

The Code Looks Like this:

program formatter (...);

VAR DIR: 0..1; {Direction to Add Extra Spaces}.. Procedure Justify

(...); begin Dir: = 1 - DIR; {Opposite Direction from last time} ... End; ...

Begin {main routine of formatter} DIR: = 0; ... END;

The Declaration, Initialization and Use of the Variable Dir Are Scattered All

Over the program, liter ally hundreds of lines apart. in c or fortran, DIR

Can Be Made Private To The Only Routine That Needs to Know About IT:

... main () {...}

...

Justify () {static int Dir = 0;

DIR = 1 - DIR; ...}

There isfles of the Same Problem on a larser

Functions for Buffered I / O, Storage Management, and Symbol Tables All Spring

TO MIND.

There Are At Least Two Related Problems. Pascal Provides No Way To Initialize

Variables Stati Cally (I.E., At Compile Time); There is nothing analogous to

Fortran's Data Statement Or Initializers Like

INT DIR = 0;

IN C. This Means That A Pascal Program Must Contain Explicit Assignment

Statements to Initialize Variables (LIKE THE

DIR: = 0;

Above). This Code Makes The Program Source Text Bigger, And The Program

Itself Bigger At Run Time.

Furthermore, The lack of initializers exacerbates the problem of going-lad

Scope caused by the lats of a static storage class. The time to initialize

Things is at the beginning, so Either the main routine itself begins with a

Lot of Initialization Code, or it calls one or more routines to do the

Initializations. in Either Case, Variables to Be Initialized Must Be Visible,

Which means in effect at the highest level of there hierarchy. The result is

That Any Variable That Is To Be Initialized Has Glo Bal Scope.

THIRD DIFFICULTY IS That there is no way for two routines to share a

Variable unless it is declared at OR Above Their Least Common Annestor.Fortran Common and C's External Static Stor Age Class Both Provide a Way for

Two routines to cooperate privately, WITHOUT Sharing Informa Tion with THEIR

Ancestors.

The New Standard Does Not Offer Static Variables, Initialization OR

Non-hierarchical commu nication.

2.3. Related Program Components Must Be Kept Separate

Since the Original Pascal Was Implement with a one-pass compiler, The

Language Believes Strongly in Declaration Before Use. in particular,

Procedures and functions Must Be Declared (Body and all) Before the isy.

The result is what a type A Typical Pascal Program Reads from the Bottom Up - All

The Procedures and Functions Are Displayed Before Any of The Code That Calls

THEM, AT All levels. this is essential ipposite to the order in which the

Functions Are Designed and used.

To Some Extent this can be mitigated by a mechanism like the #include facility

Of C and Ratfor: Source Files Can Be Included Where Needed WITHOUT CLUTTERING

Up the program. #include is not part of standard pascal, although the ucb, vu

And WhitesMiths Compilers All Provide It.

There is also a forward declaration in Pascal That Permits Separating The

Declaration of the function or procedure header from the body; it is intended

For Defining Mutually Recursive Proce Dures. When the Body Is Declared Later

ON, The Header On That Declaration May Contain Only The Function Name, And

Must Not Repeat The Information from The First Instance.

A Related Problem Is That Pascal Has A Strict ORDER IN WHICH IT IS WILLING TO

Accept Declara Tions. Each Procedure or Function Consists

Label Label Declarations, IF Any Type Typedeclarations, if any var variable declarations, if any procedure and function

Declarations, if any begin body of function or procedure end

This Means That All Declarations of One Kind (Types, for Instance) Must Be

Grouped Together for the Convenience of The Compiler, Even WHEN THE PROGRAMER

Would Like to Keep Together Things That Are Logically Related So as To

Understand The Program Better. Since a Program Has To Be Presened to the THE

Compiler All at ONCE, IT IS RARELY POSSIBLE TO Keep The Declaration,

Initialization and use of types and variables close together. Even Some of

The Most Dedicated Pascal Supporters Agree: 14

`` The inabino to make such groupings in structuring large programs is one of

Pascal's Most FrustRating Limitations. ''

A File Inclusion Facility Helps Only A Little Here.

The New Standard Does Not Relax The Requirements on The Order of Declarations.

2.4. There is no separate compilation

The `` official '' Pascal Language Does Not Provide Separate Compilation, And So

EACH IMPLE MANTATION DECIDES ON ITS OWN What To Do. Some

Interpreter, for instance (this is closeest to the spirit)

Of the language and matches the letter exactly. Many Others Provide A

Declaration That Specifies That The Body of a Function Is External Defined.

In Any Case, All Such Mechanisms Are Non-Standard, and Thus Done Differently

By Different Systems.

THEORETICLY, THE IS No NEED for Separate CompiLation - IF One's Compiler

Is Very Fast (and if the source for all routines is always available andiff

One's Compiler Has A File Inclusion Facility So That Multiple Copies of Source Not NEEDED, Recompiling Everything Is Equivalent. in Practice, Of

Course, Compilers Are Never Fast Enough And Source Is Offen Hidden and File

Inclusion is not part of the language, so changes are time Time-consuming.

Some Systems Permit Separate Compilation But Do Not Validate CONSISTENCY OF NOT VALIDATE

Types across the boundary. This Creates a giant hole in the strong type.

(Most Other Languages ​​Do No Cross Compilation Checking Either, So Pascal IS

NOT INFERIOR in this respect.) i Have Seen At Least One Paper (MerciFully

UNPUBLISHED THATIGATES C for Failing to Check Types Across

SEPA RATE COMPILATION BOUNDARIES while suggesting on page n 1 That the Way To

Cope with Pascal Is To Compile Procedures Separately to Avoid Type Checking.

The New Standard Does Not Offer Separate CompiLation.

2.5. Some Miscellaneous Problems of Type and Scope

Most of The Following Points Are Minor Irritations, But I Have To Stick Them

In somewhere.

IT is not legal to name a non-basic type as the literal formal parameter of a

Procedure; the folowing is not allowed:

Procedure add10 (var A: array [1..10] of integer;

Rather, One Must Invent a Type Name, Make A Type Declaration, And Declare T

Formal Parameter to Be An Instance of That Type:

TYPE A10 = Array [1..10] of integer; ... Procedure Add10 (Var A: A10);

Naturally the Type Declaration is Physical Separated from the Procedure That

Uses it. The disci pline of inventing type names is helpful for types That

Are used offen, but it is a distraction for things ready.

IT is nice to have the declaration var for formal parameters of functions and

Procedures; The Procedure Clearly States That IT INTENDS TO MODIFY THEARGUMENT. But The calling program Has No Way to declare what a variable is to

Be modified - the information is on - one place, While Two Places Would Be

Better. (Half a Loaf Is Better Than None, Though - Fortran Tells The User

Nothing about who will do what to variables.)

IT IS Also a minor bother what arrays area passed by value by default - the

Net Effect Is That Every Array Parameter Is Declared Var by The Programmer

More or less without thinking. if the var deflarative is inadvertly

Omitted, The Resulting Bug is stock.

Pascal's Set Construct Seem Like a Good Idea, Provinceing Notationalal

Convenience and some free type checking. for example, a set of tests like

IF (c = blank) or (c = tab) or (c = newline) Then ...

Can Be Written Rather More Clearly and Perhaps More EfficIntly AS

IF C in [Blank, Tab, Newline] Then ...

BUT IN Practice, Set Types Are Not Useful for Much More this, Because The

SIZE OF A Set IS STRONGLY IMPLEMENTATION Dependent (Probably Because It Was So

In The Original CDC Implementa Tion: 59 Bits). for example, IT IS Natural To

Attempt to Write the Function Isalphanum (C) (`` is c alphaumeric? ') AS

{Isalphanum (c) - True if c is letter or digit} function isalphanum (C:

Char): boolean; begin isalphanum: = c in ['a' .. 'z', 'a' .. 'z', '0' .. '9'] end;

But in Many Implementations of Pascal (Including The Original) This Code Fails

Because sets are just too small. accordingly, sets area generally best left

Unuse if one intends to write portable pro grams. (this specific routine

Also Runs An Order of Magnitude Slower with sets Than with a range test Orarray Reference.)

2.6. There is no escape

There is no way to overrides the Type Mechanism When Necessary, Nothing

Analog to the `` Cast '' Mechanism In C. this Means That IT IT Possible

To Write Programs Like Storage Alloca Tors or I / O Systems in Pascal, Because

There is no way to talk about the type of object what the return, and no way

To Force Such Objects Into An Arbitrary Type for Another Use. (Strictly

Speaking, There Is A Large Hole in The Type-Checking Near Variant Records,

Through Which Some Otherwise Illegal Type Mismatches Can Be Obtained.)

3. Control Flow

The Control Flow Deficiencies of Pascal Are Minor But Numerous - The Death of

A THOUSAND CUTS, Rather Than A Single Blow to a Vital Spot.

There is no guaranteed Order of evataration of the logical Operators and AND 

- Nothing Like && and || in C. This Failing, Which Is Shared with Most Other

Languages, Hurts Most offten in loop control:

While (i <= xmax) and (x [i]> 0) DO ...

Is extremely unwise pascal usage, since there is no way to ensure what I is

Tested Before x [i] IS.

By The Way, The Parentheses in this code is Mandatory - The Language HAS

Only Four Levels of Operator Precedence, with reason..

There is no break statement for exiting loops. This is constent with the

One Entry-One Exit Philosophy Espoused by Proponents of Structured

Programming, But it does Lead to Nasty Cir Cumlocurns or Duplicated Code,

Particularly When Coupled with the inhibility to control the order in which

Logical Expressions Are Evaluated. Consider this Common Situation, Expressed

IN C or Ratfor:

While (getNext (...) {if (Something) Break rest of loop} with no break statement, The First Attempt in Pascal IS

DONE: = false; while (not done) and (getnext (...) DO if Something the Done

= True Else Begin Rest of loop end

But this doesn't work, because there is no way to force the `` Not done '' to be

Evaluated Before The Next Call of getNext. this Leads, After Several False

Starts, to

DONE: = false; while not done do beg, done: = getNext (...); if Something Then

DONE: = True Else if not done dam rest of loop end end

Of Course Recidivists Can Use A Goto and A Label (Numeric Only and It Has To

Be declared) To EXIT a loop. Otherwise, Early EXITS Are A Pain, Almost Always

Requiring the invention of a boolean vari able and a certain amount of

Cunning. Compare Finding The Last Non-Blank in an Array In Ratfor:

For (i = max; i> 0; i = i - 1) IF (Arr (i)! = ') BREAK

With Pascal:

DONE: = false; i: = max; while (i> 0) AND (not done) do if arr [i] = '' THEN

i: = i - 1 else done: = true;

The index of a for loop is undefined Outside the loop, so it is not possible

TO Figure Out WHETHER ONE WENT to the end or not. The increment of a for loop

Can Only Be 1 OR -1, A Minor Restriction.

There is no return statement, again for one in-one out reason. A function

Value is returned by Setting The value of a pseudo-variable (as in fortran),

THEN FALLING OFF The end of the function. this Sometimes Leads to Contipes

To make Sure That All Paths actual get to the end of the function with the

Proper value. There is also no standard way to terminate Execution Except By

Reaching the end of the outermost block, Alth City Many Implementations Providea Halt That Causes Immediate Termination.

The Case Statement Is Better Designed Than, Except That there is no

Default Clause and the Behavior Is undefined if The Input Expression Does Notes Notes Not The INPUT

Match any of the case. this crucial omission renders the case construct

Almost Worthless. In Over 6000 Lines of Pascal in Software Tools in Pascal, i

Used It Only Four Times, Although If There Had Been A Default, A Case Would

Have Served in at Least A dozen Places.

The New Standard Offers No Relief on Any of these Points.

4. The environment

THE PASCAL RUN-TIME ENVIRONMENT IS Relatively Sparse, and there is no

Extension Mechanism Except Perhaps Source-Level Libraries in The `` Official ''

Language.

Pascal's Built-In I / O Has A Deservedly Bad Reputation. It believes strongly

IN Record Oriented Input and Output. It also Has A Look-ahead Convention That

Is Hard to Implement Prop Erly in An Intective Environment. Basically, THE

Problem is what the the I / o system believes That It Must Read One Record Ahead of

The Record That Is Being Processed. in An Intective System, this Means That

When a Program Is Started, ITS First Operation is to try to read the terminal

For The First Line of Input, Before Any of The Program Itself Has Been

Executed. But in the program

Write ('please enter your name:'); read (name); ...

Read-ahead causes the program to hang, waiting for input before printing the

Prompt That Asks for IT.

IT IS Possible to escape Most of the Evil Effects of this I / O Design By Very

Careful Implemen TATION, But Not All Pascal Systems Do So, And in Any Case IT

Is relatively costly.

The I / O Design Reflectes The Original Operating System Upon Which Pascal WasDesigned; Even Wirth Acknowledges That Bias, Though Not ITS Defects. 15 IT IS

Assuty That Text Files Consist of Records, That IS, LINES OF TEXT.WHEN THE

Last Character of a Line is Read, The Built-in Function Eoln Becomes True; AT

That Point, One Must Call Readln To Initiate Reading a New Line and Reset

Eoln. Similarly, When the Last Character of The File Is Read, The Built-in EOF

Becomes True. in Both Cases, Eoln and Eof Must Be Tested Before Each Read

Rather Than After.

Given this, consIndable Pains Must Be Taken To Simulate Sensible Input. This

Implementa Tion of Getc Works for Berkeley and Vu I / O Systems, But May Not

Necessarily Work for Anything else:

{Getc - Read Character from Standard Input} Function Getc (VAR C:

Character: Character; VAR CH: Char; Begin IF EOF THEN C: = Endfile Else IF

Eoln Then Begin Readln; C: = Newline End else Begin Read (CH); C: = ORD (CH)

End; Getc: = c end;

The Type Character Is Not The Same As Char, Since Endfile and Perhaps Newline

Are Not Legal Values ​​for a char variable.

There is no notion at all of access to a file system except for predefined

Files named by (in effect) Logical Unit Number in The Program Statement That

Begins Each Program. This Apparently Reflects The CDC Batch System in Which

Pascal Was Originally Developed. A File Variable

Var fv: File of Type

IS a Very Special Kind of Object - IT Cannot Be Assigned To, NOR Used Except

By Calls to Built-in Pro Cedures Like Eof, Eoln, Read, Write, Reset and

Reset Rewinds a file and makes it ready for re-recaps; REWRITE

Makes a file ready for Writing.)

Most Implementations of Pascal Provide an escape hatch to allow access tofiles by name from the outside eNVIRONMENT, But Not Conveniently and Not

Standardly. for Example, Many Sys Tems Permit A FileName Argument in Calls To

RESET and REWRITE:

RESET (FV, FileName);

But Reset and Rewrite Are Procedures, Not Functions - There is no status

Return and no way to regain control if for some reason the attempted access

(UCSD Provides a Compile-Time Flag That Disables The Normal Abort.)

And Since Fv's Cannot Appear in Expressions Like

Reset (fv, filename); if fv = five ...

There is no escape in That Direction Either. This Straitjacket Makes IT

Essentially Impossible to Write Programs That Recover from Mis-Spelled File

Names, etc. I Never Solved it adequately in the tools revision.

There Is No Notion of Access To Command-Line Arguments, Again Probably

Reflecting Pascal's Batch-Processing Origins. Local Routines May Allow IT by

Add Non-Standard Procedures to the Environment.

Since it is not Possible to Write a General-Purpose Storage Allocator in IN

Pascal (There Being No Way To Talk About The Types That Such A Function Would

Return, The Language Has A Built-in Proce Dure Called New That Allocates

Space from a heap. Only Defined Types May Be Allocated, So it is not possible

To Allocate, for Example, Arrays of Arbitrary Size to Hold Character Strings.

The Point Ers Returned by New May Be Passed Around But Not Manipulated: There

Is No Pointer Arithmetic. There is no way to regain control if storage runs

OUT.

The New Standard Offers No Change In any of these.

5. Cosmetic Issues

Most of these Issues Are Irksome To An Experienced Programmer, And Some Are

Probably a nuisance even to beginners. All Can Be Lived with Most Other Algol-Inspired Languages, Uses The SEMICOLON

AS A State Ment Separator Rather Than a Terminator (as it is in pl / i and c).

As A Result One Must Have A Rea Sonably Sophistated Notion of What A

Statement Is to Put Semicolons in Properly. Perhaps More Important, IF ONE IS

Serious About Using Them in The Proper Places, a Fair Amount of Nuisance Edit Edit

ING IS NEEDED. Consider The First Cut AT A Program:

IF a life b; c;

But if Something Must Be Inserted Before B, IT NO LONGER Needs A Semicolon,

Because it now pre cedes an end:

IF a. "B END; C;

Now if we add an else, we must remove the semicolon on the end:

IF a the begin b0; b end else d;

And So On and So ON, with SEMICOLONS RIPPLING UP AND DOWN THE PROGRAM AS IT

Evolves.

One Generally Accepted Experimental Result In Programmer Psychology Is That

SEMICOLON As Separator Is About Ten Times More Prone to Error Than SEMICOLON

AS Terminator. 16 (in ada, 17 the MOST SIGNIFICANT LANGUAGE BASED ON PASCAL,

Semicolon Is a Terminator.) Fortunately, in Pascal One Can Almost Always

Close One's Eyes and Get Away with a semicolon as a terminator. The Excep

Tions Are in Places Like Declarations, WHERE The Separetor vs. Terminator

Problem Doesn't Seem As Serious Anyway, And Just Before Else, Which IS Easy To

REMEMBER.

C and Ratfor Programmers Find Begin and End Bulky Compared to {and}.

A Function name by itself is a call of what function; there is no way to TO

DISTINGUISH Such a Function Call from a Simple Variable Except by Knowing T

Names of the functions. Pascal Uses the fortran trick of haVing the function

Name Act Like a Variable WTHINITRIABLE, AND CAN APPEAR in Expressions, In Pascal,

ITS APPEARANCE IN EXPRESSION IS A Recursive Invocation: IF F IS A

ZERO-Argument Function, F: = F 1 IS A Recursive Call OF F.

There is a paucity of operatosis (probably related to the paucity of precedence

Levels. in particular, there is no bit-manipulation Operators (and, OR,

XOR, ETC.). I Simply Gave Up Trying to Write The Following Trivial Encryption

Program in Pascal:

I: = 1; while getc (c) <> endfile do begc (xor (c, key [i])); i: = i mod

Keylen 1 End

Because I COULDN'T Write a Sensible XOR Function. The Set Types Help A Bit

Here (So to Speak), But Not Enough; People Who Claim That Pascal Is A SYSTEM

Programming language have generally overlooked this point. for example, [18,

p. 685]

`` Pascal is at the present time [1977] The best language in the public domain

For pur poses of system programming and software importation. ''

Seems a bit naive.

There is no null string, Perhaps Because Pascal Uses the doubled quote

NOTATION TO INDICATE A Quote Embedded In A String:

'This is a' 'character'

There is no way to put non-graphic symbols intess. In Fact, Non-graphic

Characters Are Unpersons in A Stronger Sense, Since They Are Not Mentioned in

Any Part of The Standard Language. Concepts Like Newlines, Tabs, And So On Are

Handled on Each System in an ad hoc manner, usually by knowing Something About

The Character Set (E.G., ASCII NEWLINE HAS DECIMAL VALUE 10).

There Is No Macro Processor. The const mechanism for defining manifest

Constants Takes Care of About 95 Percent of The Uses of Simple #definestatements in C, But More Involved Ones Are Hopless. It is ceertainly

Possible to Put A Macro Preprocessor on a Pascal Compiler. This allowed me to

Simulate a Sensible Error Procedure AS

#define error (s) begin writeln (s); halt end

(Halt in turn might be defined as a branch to the end of the outermost block.)

Then Calls Like

Error ('Little String'); Error ('MUCH BIGGER STRING');

Work Since Writeln (As Part of The Standard Pascal Environment) Can Handle

Strings of any size. it is unfortunate That there is no way to make this

CONVENIENCE AVAILALALAL.

The Language Prohibits Expressions in Declarations, So It Is Not Possible To

Write Things Like

Const size = 10; type arr = array [1..size 1] of integer;

OR EVEN SIMPLER AONES LIKE

Const size = 10; size1 = size 1;

6. Perspective

The Effort to Rewrite The Program in Software Tools Started In March, 1980,

And, In Fits and Starts, Lasted UnTil January, 1981. The Final Product 19 WAS

Published in June, 1981. During this time i gradually adapted to most of the

Superficial Problems With Pascal (Cosmetics, The INADE QUACIES OF Control

Flow), And Developed Imperfect Solutions to the Significant Ones (Array Sizes,

Run-time environment.

The Programs in The Book Are Mannt To Be Complete, Well-Engineered Program

That Do Non-Trivial Tasks. But They Do Not Have To Be Effect, Nor Are

Their Interactions with the Operat Ing System Very Complicated, SO I WAS ABLE

To get by with some pretty kludgy solutions, Ones That Simply Wouldn't work

For real programs.

There is no significant way in Which i Found Pascal Superior To C, But Thereare Several Places Where It is a Clear Improvement over Ratfor. MOST OBVIOS

BY FAR IS Recursion: Several Pro Grams Are Much Cleaner When Written

Recursively, NOTABLY THE PATTERN-Search, Quicksort, And Expression Evaluation.

ENUMERATION DATA TYPES Are A Good Idea. They Simultaneously Delimit The Range

of legal values ​​and document theme. Records Help to group related variables.

I Found Relatively Little Use for Pointers.

Boolean Variables Are Nicer Than Integers for Boolean Conditions; The Original

Ratfor Pro Grams Contained Some Unnatural Constructions Because Fortran's

Logical Variables Are Badly Designed.

Occasionally Pascal's Type Checking Would WARN OF A SLIP of the HAND IN

Writing a Program; The Run-Time Checking of Values ​​Also Indicated Errors from

Time to Time, Particularly Subscript Range ViOLATIONS.

Turning to the Negative Side, Recompiling a Large Program from Scratch To

Change a single line of source is extremely tiresome; Separate CompiLation,

With or welch type checking, IS Mandatory for Large Programs.

I Derived Little Benefit from The Fact That Characters Are Part of Pascal and

NOT Part of For Tran, Because The Pascal Treatment of strings and non-graphics

IS So INADequate. in Both Lan Guages, IT IS Appallingly Clumsy to Initialize

LITERAL STRINGS for Tables of Keywords, Error Messages, And The Like.

The finished programs are in General About The Same Number of Source Lines AS

THEIR RATFOR Equivalents. at first this surprised me, Since My Preconception

Was That Pascal Is A Wordier and Less Expressive Language. The Real Reason

SEEMS to Be That Pascal Permits Arbitrary Expressions in Places Like Looplimits and Subscripts Where Fortran (That IS, Portable Fortran 66) Does Not,

So Some Useless Assignments Can Be Eliminated; Furthermore, THE RATFOR

Programs Declare Functions While Pascal Ones Do Not.

To Close, Let Me Summarize The Main Points in The Case Against Pascal.

1. Since the size of an array is part of its type, it is not possible to

Write General-Purpose Rou Tines, That IS, To DEAL WITH ARRAYS OF DIFFERENT

Sizes. in particular, String Handling is very diff ficult.

2. The lack of static variables, initialization and a way to communicate

Non-hierarchically combine to destroy the `` locality '' of a program -

Variables Require Much More Scope Than ught to.

3. The one-pass nature of the language forces procedures and functions to be

Presented in An Unnatural ORDER; The Enforced Separation of Various

Declarations Scatters Program COMPO NENTS That Logically Belong Together.

4. The Lack of Separate Compilation Impedes The Development of Large Programs

And Makes The Use of Libraries Impossible.

5. The Order of Logical Expression Evaluation Cannot Be Controlled, Which

Leads to convoluted code and extraneous variables.

6. The Case Statement Is Emasculated Because The Is No Default CLAUSE.

7. The Standard I / O Is Defective. There is no Sensible Provision for Dealing

With Files or Pro Gram arguments as part of the standard logage, and no

EXTENSION MECHANISM.

8. The Language Lacks Most of the Tools Needed for Assembling Large Program,

MOST NOTABLY FILE Inclusion.

9. There is no escape.

This Last Point Is Perhaps The Most Important. The Language IS INADEQUATE BUT

Circum Scribed, Because The the no way to escape it ipts to disable the Type Checking When Necessary. There is no way

Replace the Defective Run-Time Environment with a Sensible One, Unless ONE

Controls The Compiler That Defines The `` Standard Procedures. '' 'The Lan Guage

IS closed.

People Who Use Pascal for Serious Programming Fall Into A Fatal Trap. Because

The Language IS SO Impotent, It Must Be Extended. But Each Group Extends

Pascal in Its Own Direction, To Make It Look Like Whatver Language They

Really Want. Extensions for Separate Compilation, Fortran Like Common, String

Data Types, Internal Static Variables, Initialization, Octal Numbers, Bit

Opera Tors, Etc., All add to the utility of the language for one group, but BUT

Destroy its portability to ta.

I feel this is a missake to use pascal for anything much beyond its

ORIGINAL TARGET. ITS Pure Form, Pascal IS A Toy Language, Suitable for

Teaching But not for real programming.

Acknowledgments

I am Grateful To Al Aho, Al Feuer, Narain Gehani, Bob Martin, Doug Mcilroy,

Rob Pike, Dennis Ritchie, Chris Van Wyk and Charles Wetherell for Helpful

Criticisms of Earlier Versions of this Paper.

1. Feuer, A. R. And N. H. Gehani, `` A Comparison of The Programming Languages

C and Pascal - Part i: Language Concepts, '' Bell Labs Internal Memoralum

(September 1979).

2. N. H. Gehani and A. R. Feuer, `` a commitrison of the programming language

C and Pascal - Part II: Program Properties and Programing Domains, '' Bell

Labs INTERNAL MEMORANDUM (February 1980).

3. P. Mateti, `` `` Pascal Versus C: a Subjective Comparison, '' Language Design

And Programming Methodology Symposium, Springer-Verlag, Sydney, Australia (September 1979).

4. A. Springer, `` `COMPARISON OF LANGUAGE C and PASCAL, '' IBM Technical

Report G320-2128, CAM Bridge scientific center (August 1979).

5. B. W. Kernighan and P. J. Plauger, Software Tools, Addison-Wesley,

Reading, Mass. (1976).

6. K. Jensen, Pascal User Manual and Report, Springer-Verlag (1978). (2nd).

Edition.)

7. David v. Moffat, `` a categorized Pascal Bibliography, '' Sigplan Notices

15 (10), PP. 63-75 (October 1980).

8. A. N. Habermann, `` Critical Comments on The Programming Language

Pascal, '' Acta Informatica 3, PP. 47-57 (1973).

9. O. Lecarme and P. Desjardins, `` `on the programming logage

Pascal, '' Acta Infor Matica 4, PP. 231-243 (1975).

10. H. J. Boom and E. Dejong, `` a critical comparison of several programming

LANGUAGE IMPLEMENTA TIONS, '' Software Practice and Experience 10 (6),

PP. 435-473 (June 1980).

11. N. Wirth, `` an assessment of the programming language pascal, '' IEEE

TRANSACTIONS ON SOFTWARE ENGI Neering SE-1 (2), PP. 192-198 (June, 1975).

12. O. Lecarme and P. Desjardins, IBID, P. 239.

13. A. M. Addyman, `` a Draft Proposal for Pascal, '' Sigplan Notices 15 (4),

PP. 1-66 (April 1980).

14. J. Welsh, W. J. Sneeringer, And C. A. R. Hoare, `` Ambiguities and

Insecurities in Pascal, '' Software PRAC Tice and Experience 7, PP. 685-696

(1977).

15. N. Wirth, IBID., P. 196.

16. J. D. Gannon and J. J. Horning, `` Language Design for Programing

Reliability, '' 'IEEE TRANS. Software Engineering SE-1 (2), PP. 179-191 (June

1975).

17. J. D. Ichbiah, et al, `` Rational for the design of the ada programmingLanguage, '' Sigplan Notices 14 (6) (June 1979).

18. J. Welsh, W. J. Sneeringer, And C. A. R. Hoare, IBID.

19. B. W. Kernighan and P. J. Plauger, Software Tools in Pascal,

Addison-Wesley (1981).

转载请注明原文地址:https://www.9cbs.com/read-26789.html

New Post(0)