Cmpe 104
Download
1 / 60

CMPE 104 - PowerPoint PPT Presentation


  • 93 Views
  • Uploaded on

CMPE 104. Pascal (Modified slides of Tom Rethard). Pascal. Designed by Niklaus Wirth Development started in 1968 First working compiler in 1970 Pascal-70 Report was on 29 pages. Pascal Goals. Goals It is teaching language Reliability Simplicity Efficiency Wirth:

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' CMPE 104' - fleur-castaneda


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Cmpe 104

CMPE 104

Pascal(Modified slides of Tom Rethard)


Pascal
Pascal

  • Designed by Niklaus Wirth

  • Development started in 1968

  • First working compiler in 1970

  • Pascal-70 Report was on 29 pages


Pascal goals
Pascal Goals

  • Goals

    • It is teaching language

      • Reliability

      • Simplicity

      • Efficiency

    • Wirth:

      “the principle to include features that were well understood, in particular by implementers, and to leave out those that were still untried and unimplemented, proved to be the most successful single guideline.”

  • The language is suitable for teaching programming in a systematic way.

  • The implementation of the language is reliable and efficient, at compile-time and run-time, on all available computers.


Example
Example

Program AbsMean (input, output);const Max = 900;type index = 1 .. Max;var N: 0 .. Max; Data: array [index] of real; sum, avg, val: real; i: index;…


Example con t
Example (con’t)

beginsum := 0;readln (N);for i := 1 to N do begin readln (val); if val < 0 then Data[i] := val else Data[i] := val end;for i := 1 to N do sum = sum + Data[i];avg := sum/N;writeln (avg);

end.


Enumerations
Enumerations

Type DayOfWeek = (Sun, Mon, Tue, Wed, Thu, Fri, Sat); Month = (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec);var today, tomorrow: DayOfWeek;begin…today := Tue;tomorrow := today + 1;…today = Jan; /* type error …



Subrange types
Subrange Types

var DayOfMonth 1 .. 31;

  • Restricts the range of values for DayOfMonth to the integer subrange of 1..31

  • Can also use in enumerations:

    Type WeekDay = Mon .. Fri;


Sets

  • Set of <ordinal type>

    (enumeration type(char,Boolean),

    subrange type)

  • Var S, T: set of 1..10;

  • S := [1, 2, 3, 5, 7];

  • T := [1 ..6];

  • If T = [1, 2, 3, 5] then …


Set operations
Set Operations

  • =

  • <>

  • <= subset or equal

  • >=

  • But: no < or > !


Arrays
Arrays

  • Any upper or lower bound

  • Can also use enumeration types as array indices

  • Examples

    var A: array [1 .. 100] of real;

    var HoursWorked: array [Mon .. Fri] of 0 .. 24;


Arrays1
Arrays

Var day: Mon .. Fri; TotalHours: 0..120;begin TotalHours := 0; for day := Mon to Fri do TotalHours := TotalHours + HoursWorked[day];


Arrays of characters
Arrays of Characters

Any finite discrete type for index

var Occur: array [char] of integer; …Occur[ch] := Occur[ch] + 1; …if Occur[‘e’] > Occur[‘t’] then …


More complex arrays
More Complex Arrays

var M: array [1..20] of

array [1 .. 100] of real;orvar m: array [1 .. 20, 1 .. 100] of real;


More on arrays
More on Arrays

  • Need to be static, not dynamic

    • Must know types at compile time

    • Dimensions are part of the array type

    • Arrays are considered the same type if index types and base types both match


Type problems
Type problems

type vector = array [1 .. 100] of real;var U, V, vector;function sum (x: vector): real; …begin … end {sum};

  • Can write

    var W: array [1 ..75] of real;

  • But cannot write:

    Sum(W)


Type problems1
Type Problems

  • Types of W and of x are not the same because the ranges of the indices are different!


Record types
Record Types

  • Heterogeneous data

  • Multiple components

  • Various types


Records
Records

type

person = record name: string; age: 16 .. 100; salary: 10000 .. 100000; sex: (male, female); birthdate: date; hiredate: date;end;string = packed array [1 ..30] of char;date = record mon: month; day: 1 ..31; year: 1900 .. 2100;end;month = (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec);


Using a record
Using a Record

  • To use a record:var newhire: person;just like any other type


Getting to the components
Getting to the Components

varnewhire: person;today: date;…newhire.age := 25;newhire.sex := female;newhire.date := today;


More possibilities
More Possibilities

if newhire.name[1] = ‘A’ then …

type employeeNum = 1000 .. 9999;var employees: array [employeeNum] of person; EN: employeeNum;


Making it simpler
Making it Simpler

with newhirebegin age := 25; sex := female; date := todayend;


Storage groupings
Storage Groupings

  • Homogeneous

    • Arrays

    • All elements are the same type

    • Computed (dynamic) selector (subscript or index)

  • Heterogeneous

    • Records

    • Elements (components) may be of different types

    • Static selector


Variant records
Variant Records

  • Sometimes records vary from one record type to another.

  • Think of this as a primitive form of subclassing


Variant records1
Variant Records

type plane = record flight: 0 .. 999; kind: (B727, B737, B747); status (inAir, onGround, atTerminal); altitude: 0 .. 100000; heading: 0 .. 359; arrival: time; destination: airport; location: airport; runway: runwayNumber; parked: airport; gate: 1.. 100; departure: time;end; {plane}


What s wrong
What’s Wrong?

  • Not all data has meaning at the same time.

  • Can imply a plane is located at one airport and is parked at another

  • Violates security principle.


Variant records2
Variant Records

type plane = record flight: 0 .. 999; kind: (B727, B737, B747); case status: (inAir, onGround, atTerminal); inAir:( altitude: 0 .. 100000; heading: 0 .. 359; arrival: time; destination: airport); onGround: ( location: airport; runway: runwayNumber); atTerminal: ( parked: airport; gate: 1.. 100; departure: time);end; {plane}


Implementation
Implementation

flightkindstatus

altitudeheadingarrivaldestination

locationrunway

parkedgatedeparture


The dreaded pointer
The Dreaded Pointer

  • There is a problem with pointers and strong typing!

  • Pascal solves this problem by typing pointers


Typed pointers
Typed Pointers

var p: ^real; x: real; c: char;begin new(p); p^ := 3.14159; c := p^; {illegal}end


Pointers with records
Pointers with Records

var p: ^plane;begin … p^.plane.parked[1] … …end;


Interpretations for equivalency
Interpretations for equivalency

  • Structural equivalence

    • Structural descriptions of the types be the same

  • Name equivalence

    • Names must be same


Structural equivalence
Structural Equivalence

var

x: record id: integer; weight: real end;

y: record id: integer; weight: real end;

  • The above are the same because their structure is the same


But consider this
But… Consider this

typeperson = record id: integer; weight: real end;car = record id: integer; weight: real end;

  • The above are the same because their structure is the same, so:car := person;according to structural equivalency is legal!


Name equivalence
Name Equivalence

varx: record id: integer; weight: real end;y: record id: integer; weight: real end;

  • Is actually ambiguous,

  • Different versions of Name Equivalence Rule differ on this example.

    • If reinterpreted as follows, then they are different

      type

      T00029: record id: integer; weight: real end;

      T00030: record id: integer; weight: real end;

      varx: T00029;y: T00030;


Name equivalence issues
Name Equivalence Issues

type age = 0 .. 150;

var n: integer;a: age;

  • Is n:= a legal?

    • Pure name equivalence says no

    • Logic says yes

    • Revised Pascal Report says that a subrange of a type is still that type


Comparison
Comparison

  • Name Equivalence generally safer

    • More restrictive

  • Name Equivalence is easier to implement

    • Simply a string comparison

    • Structural equivalence requires a recursive function

  • ISO Pascal specifies name Equivalence


Name structures
Name Structures

  • Pascal provides six types

    • Constant bindings

    • Type bindings

    • Variable bindings

    • Procedure and function bindings

    • Implicit enumeration bindings

    • Label bindings


Constant bindings
Constant bindings

  • const MaxData = 100;

  • MaxData can be used almost anywhere

    • All declarations

    • Executable statements (for loops, etc.)

    • Expressions

    • BUT, not in other const declarations!

      • const MaxDataMinus1 = MaxData –1; is not allowed


Constructors
Constructors

  • Record constructors

  • Procedure/Function

    • The major scope defining construct


Procedures
Procedures

procedure <name> (<formal arguments>); <declarations>begin <statements>end;


A problem
A Problem

procedure P (...); ...begin ...

Q(...) ...end;

procedure Q (...); ...begin ... P(...) ...end;


A problem solved
A Problem Solved

procedure Q(...) forward;

procedure P (...); ...begin ...

Q(...) ...end;

procedure Q (...); ...begin ... P(...) ...end;


Procedure construction
Procedure Construction

procedure <name> (<formal arguments>); <label declarations> <const declarations> <type declarations> <var declarations> <procedure and function declarations>begin <statements>end;


Pascal eliminates the block
Pascal eliminates the block

  • Simplifies name structure

  • Complicates efficient use of memory


Control structures
Control structures

  • Reflects structured programming ideas


For loop
For Loop

for <name> := expression { to | downto } <expression> do <statement>

Bounds of the loop are computed once, at loop entry => definite iterator


While loop
While Loop

  • Also a “Leading Decision Indefinite Iterator”

    while <condition> do <statement>

  • Checks at top of loop

  • Can use “while true do....” for a loop exiting from the middle (Mid-Decision Iterator)


Repeat loop
Repeat Loop

  • Also “Trailing Decision Indefinite Iterator”

    repeat <statement> until <condition>

  • Checks at bottom of loop


Unlabeled case statement
Unlabeled Case Statement

  • Modeled according to Fortran computed goto

    case <expression> of <statement>, <statement>, ... <statement>end case;


case I ofbegin ... S1 ... end;begin ... S2 ... end;

begin ... S3 ... end;begin ... S4 ... end;end case;

No labels are provided.


Labeled case statement
Labeled Case Statement

  • Major contribution of Pascal

    case <expression> of <case clause>; <case clause>; ... <case clause>end case;

    Designed by C.A. Hoare: the most important of his many contributions to language design


Labeled case statement1
Labeled Case Statement

case I of 1: begin ... S1 ... end; 2: 3: begin ... S23 ... end; 4: begin ... S4 ... end;end case;

  • Some dialects of Pascal add an otherwise case.


Parameter passing
Parameter Passing

  • Passing by reference

    • Replaces Algol pass by name

    • Intended to allow side effects (ie, I-O parameter usage)

    • Passes only the address

  • Passing by value

    • Intended for input only parameters

    • Side effects not allowed

    • Done by copy-in


Pass as constant
Pass as Constant

  • Original specification contained this instead of pass by value

  • Similar to C const parameter passing

  • Allowed compiler to pass either address or value

  • Called procedure could not modify it

  • Elimination encourages call by reference


Procedure
Procedure

type vector=array[1..100] of real;

var A:vector

procedure P(x:vextor); \*pass by constant

begin

writeln(x[1]); A[1]:=0; writeln(x[1])

end;

begin

P(A)

end;


Pass as constant1
Pass as Constant

  • Two orthogonal issues involved

    • Should copy its value or use its address?

    • Should be I or I-O parameter

  • Approach violates the Orthogonality Principle


Procedure1
Procedure

Procedure difsq (function f:real; x:real):real

begin

difsq:= f(x*x) – f(-x*x)

end

difsq(sin,theta)=sin(theta^2 ) – sin(-theta^2)


Procedure arguments
Procedure arguments

  • The arguments of a formal procedure parameter shall be specified

    Procedure difsq (function f(y:real):real; x:real):real


ad