Subroutines Control abstraction Subroutine design If a subroutine - - PowerPoint PPT Presentation

subroutines
SMART_READER_LITE
LIVE PREVIEW

Subroutines Control abstraction Subroutine design If a subroutine - - PowerPoint PPT Presentation

Subroutine Subroutines Control abstraction Subroutine design If a subroutine does not fit on the screen, it is too long Problem should be divided into smaller pieces Subroutine = If some task X is needed twice, make it a


slide-1
SLIDE 1

189

Subroutines

  • Subroutine

– Control abstraction

  • Subroutine design

– If a subroutine does not fit on the screen, it is too long

  • Problem should be divided into smaller pieces

– If some task X is needed twice, make it a subroutine.

  • When are two seemingly different things the

same?

  • When are seemingly similar things different?

Subroutine = procedure (statement)

  • no return value
  • side effects

function (expression)

  • return value
  • (no side effects

in some languages)

slide-2
SLIDE 2

190

Terminology

  • f

subroutines

  • Subroutine header
  • Subroutine definition (prototype)
  • Subroutine body (definition)

– header (interface) ja body (functionality)

  • Subroutine call (activation)
  • Active subroutine

– When a subroutine has been called, it has started execution, but not finished it.

  • Parameters

– Formal and actual

  • Parameter profile

– Number, order, and types of formal parameters

  • name
  • Formal parameteres
  • name and type
  • Result type (function)
  • body
  • Definitions and

statements

  • (invariants)
  • (exceptions)

procedure P ( parameters ) void P ( parameters )

slide-3
SLIDE 3

191

Parameters

  • Formal parameters (header)
  • Actual parameters (call)
  • Parameter binding

– Binding actual parameters to formal

  • nes

– Type checks – Arity-check

  • (C (non-ANSI))

– (Number and types are not checked) – (A varying number of params is allowed)

  • e.g., printf ( also ANSI-C)

void fun ( i, j ) int i, j; { ... } ... fun ( 1, 2, 3 ); non-ANSI-C:

slide-4
SLIDE 4

192

Parameter passing mechanisms

  • pass-by-value
  • pass-by-result
  • pass-by-value-result
  • pass-by-reference
  • (pass-by-name)
slide-5
SLIDE 5

193

Value parameters (pass-by- value)

  • Information passing from caller

to procedue – Formal parameter is a local variable – Formal parameter gets the same value as the actual parameter at call-time – Changes in the formal parameter do not affect the actual parameter

slide-6
SLIDE 6

194

Reference parameters (pass-by- reference)

  • Passing information in both directions
  • Formal parameter is a reference to the

variable in the actual parameter

  • Variable is defined before the call and

remains the same throughout the execution

  • Changes in the formal parameter are

visible immediately in the variable

  • Requires actual parameter to be a variable

(lvalue)

  • Aliasing can occur (same variable

accessed in multiple ways)

slide-7
SLIDE 7

195

Constant reference parameters (pass-by- constant)

  • Passing information in one direction

– Formal parameter is a reference to the variable in the actual parameter – Variable is defined before the call and remains the same throughout the execution – Formal parameter cannot be changed – (Changes in actual parameter are visible in procedure) – Good if copying values is costly (memory/time)

slide-8
SLIDE 8

196

Value-result parameters

  • Like pass-by-value, but information

moves in both directions – Formal parameter is a local variable – Initial value like in pass-by-value – End value of formal parameter is copied into the actual parameter – Differences to pass-by-reference: no aliasing, no requirement for common memory (remote calls) – If exceptions occur, parameter not changed

slide-9
SLIDE 9

197

Result parameters

  • Passing information from the

procedure to the caller – Formal parameter a local variable – End value is copied into the actual paremeter – At call time no value is passed to the procedure! – Rare, can be used for "multiple return values"

slide-10
SLIDE 10

198

Pass-by- name

  • Not any more used in any major language
  • The actual parameter expression is

(re)calculated every time the formal parameter is used

  • Variable names in the parameter expression

still refer to the scope of the caller

  • (A little bit like lazy evaluation, but value is

possibly calculated several times)

  • Another interpretation: a lambda containing

the actual parameter expression is passed to the function

  • C/C++ preprocessor macro (#define)

parameters resemble pass-by-name (but not quite)

slide-11
SLIDE 11

199

Parameter passing in languages

  • Java & Python

– value parameters for primitive types – Reference parameters for classes – (depends on the definition of "variable" vs "object")

  • C

– Value parameters (array = reference) – Name parameters in #define-macros (almost)

  • C++

– Value or reference

  • Ada

– value parameters (in) – result parameters (out) – value-result or reference parameters (in out)

  • Haskell

– Think about it! ???

Name parameters in Algol60

slide-12
SLIDE 12

200

Observations about aliasing

  • Same memory location/ variable

may be referenced with multpile names

– Readability suffers! – E.g., global variable passed as reference

  • Birth of a an alias:

– Parameter passing (pass-by-reference) – Pointer/reference variables

  • Possibility of aliasing prevents

compiler optimizations

slide-13
SLIDE 13

201

Subroutine memory management

  • Static allocation (e.g., Fortran)

– Every variable is allocated at compile time – Waste of memory – Prevents recursion – Enables bad style (e.g., use of values generated at previous instances)

  • Dynamic allocation (modern pls)

– Activation records for subroutine calls – Stack allocation for activation records – Memory is allocated only when called

slide-14
SLIDE 14

202

Subroutine implementation (simple)

  • Call of subroutine

1. Pass the return address to the subroutine (PC + 1) 2. Pass the actual parameters 3. Move control to the subroutine 4. Assign local variables

  • Return from subroutine

1. Move the return value to the place reserved for it 2. Move the parameter values to the real parameters (value-result or result) 3. Move control back to the caller (return address)

Local variables Parameters Result Return address

slide-15
SLIDE 15

203

More complex subroutines

  • Recursion

– Storing program counter is not sufficient – Each recursive call has it's own parameters, local variables and return value – Dynamic link points the place of calling

  • Nested subroutines

– Static link is needed to point to the outer scope:

  • Outer subroutine execution cannot end before

all its inner subroutines have ended

  • A subroutine can call only the subroutines that

are in its scope

slide-16
SLIDE 16

204

Activation records

  • Function result: place for the return value
  • True parameters

– Value parameters: as local variables – Reference parameters: space for address/pointer

  • Return address: calltime PC + 1
  • (State: saving registers etc.)
  • Static (access) link

– Points one scope up, i.e., what is the ”parent scope”

  • Dynamic (control) link

– Old top of the stack, i.e., a calling subroutine's activation

record

  • Local variables

– Also possible temporary, compiler generated variables

Parametrit Funktion tulos Return address Parameters Static link Function result (Parametrit) (Funktion tulos) Parametrit Funktion tulos Paikalliset muuttujat Dynamic link Parametrit (Parametrit) (state) Local variables Parametrit (Parametrit) Parametrit Paikalliset muuttujat Parametrit (Parametrit) ... Local variables

slide-17
SLIDE 17

205

procedure A procedure B < point2 > end B; procedure C procedure D < point1 > B; end D; D; end C; C; end A;

Static and dynamic links

B ...

  • dyn. link
  • stat. link

D ...

  • dyn. link
  • stat. link

C ...

  • dyn. link
  • stat. link

A ...

  • dyn. link
  • stat. link

Activation record stack in point 2

slide-18
SLIDE 18

206

Code blocks

  • Can be implemented like

subroutines

– Paremeterless subroutines – Always called in the same place

  • Streamlining implementation

– The required memory for local variables

  • f the block is static

– Entry and exit to and from blocks happens in textual order of the code – Memory can be allocated after local variables

slide-19
SLIDE 19

207

Implementing blocks

void main ( ) { int x, y, z; while ( ... ) { int a, b, c; ... while ( ... ) { int d, e; ... } } while ( ... ) { int f, g; ... } ... }

C++/C/Java:

main ... ... ... x d c b / g a / f z y e Block variables main- variables

slide-20
SLIDE 20

208

Implementation

  • f lambdas
  • Lambdas are nameless functions., but can refer to

variables of the scope where they were created: they capture variables

  • When a lambda expression is evaluated, a closure is

produced: a "thing" that contains the lambda's code (function) and a reference to the lambda's environment

  • Environment reference can be implemented as pointers

to used variables only or to the entire activation record

  • What happens if a lambda outlives its environment?

(returned as return value, for example?)

  • C++: lambdas can copy the used variables instead of

using references, problem solved?

  • Many functional languages allocate activation records
  • n heap, leaving their destruction to garbage collection

(activation record can outlive its function).

slide-21
SLIDE 21

209

Parameter binding

  • Binding by position

– Binding is done according to order

  • Binding by keywords
  • Default values

procedure F ( i, j: in Integer; a, b: out Float ); ... F ( a => my_a, b => my_b, i => 0, j => 2 ); procedure Increment ( i: in out Integer; by: in Integer := 1 ); ... Increment ( x );

Ada:

slide-22
SLIDE 22

210

Rules for default parameters

  • Ada, Python
  • C++:

– Default parameters must be the last

  • nes in the list

function ComputePay ( Income: Float; Exemptions: Integer := 1; TaxRate: Float ) return Float; ... Pay := ComputePay ( 2000.0, TaxRate => 0.15 );

slide-23
SLIDE 23

211

Subroutine

  • verloading
  • Different (types of) subroutines have

the same name, the called subroutine is

identified by: – It's name – Number of parameters – Types of the parameters (statically typed languages) – Return type (in some languages)

  • Polymorpohism of basic operators

(+, -, *, /)