Subprograms function (expression) Subprogram (subroutine) - - PowerPoint PPT Presentation

subprograms
SMART_READER_LITE
LIVE PREVIEW

Subprograms function (expression) Subprogram (subroutine) - - PowerPoint PPT Presentation

Subprogram procedure (command) Subprograms function (expression) Subprogram (subroutine) statement abstraction, control abstraction Subprogram design if a subprogram does not fit on the screen, it is too long


slide-1
SLIDE 1

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

1

Subprograms

  • Subprogram (subroutine)

– statement abstraction, control abstraction

  • Subprogram design

– if a subprogram does not fit on the screen, it is too long

  • divide the solution of the problem into smaller parts

– if an action is needed twice (or more times), implement the action as a subprogram

  • when are two seemingly different things the same?
  • when are seemingly similar things different?

Subprogram

  • procedure (command)
  • function (expression)
slide-2
SLIDE 2

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

2

Subprogram terminology

function Square ( x: Integer ): Integer; begin Square := x * x end; header body subprogram name formal parameter result type

Pascal-code

slide-3
SLIDE 3

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

3

More terminology

  • f subprograms
  • Subprogram definition

– header (interface) and body (functionality)

  • Subprogram declaration (prototype)
  • Subprogram call (activation)

– active subprogram

  • Parameters

– formal and actual parameters

  • Parameter profile

– number, order, and types of the formal parameters

  • header
  • name
  • formal parameters
  • name and type
  • result type (of functions)
  • body
  • declarations and statements
  • (invariants)
  • (exceptions)

procedure P ( parameters ) void P ( parameters )

slide-4
SLIDE 4

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

4

Parameters

  • Parameter compatibility

– binding of actual parameters to formal ones – arity check – type checks

  • C-language

– K&R-C (non-ANSI-C) does not check parameter numbers nor types – ANSI-C may omit checkings – allows variant number of parameters

  • e.g. printf

void fun ( i, j ) int i, j; { ... } ... fun ( 1, 2, 3 );

non-ANSI-C:

int printf ( char *format, ... )

slide-5
SLIDE 5

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

5

Parameter binding

  • Positional parameters

– binding according to the order

  • Keyword parameters

– the name of the formal parameter is given in the call

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

Ada-code: Imaginary code:

format_page ( colums => 2, window_height => 400, window_width => 200, header_font => Helvetica, body_font => Times, title_font => Times_Bold, header_point_size => 10, body_point_size => 11, title_point_size => 13, justification => true, hyphenation => false, page_num => 3, paragraph_indent => 18, background_color => white );

slide-6
SLIDE 6

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

6

Default value parameters

  • Problem:

– Which formal parameter the actual parameter 3 is bound to?

  • Programming languages have different rules

to solve the problem

procedure P ( x: Integer := 1; y: Integer := 2 ); ... P ( 3 );

Imaginary code:

procedure Increment ( i: in out Integer; by: in Integer := 1 ); ... Increment ( x );

Ada:

slide-7
SLIDE 7

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

7

Rules for the default value parameters

  • Ada:
  • Python:

– parameters that follow absent default-value parameters must be keyword parameters

  • C++:

– default-value parameters must be the last ones in the list function ComputePay ( Income: Float; Exemptions: Integer := 1; TaxRate: Float ) return Float; ... Pay := ComputePay ( 2000.0, TaxRate => 0.15 );

Ada:

slide-8
SLIDE 8

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

8

Parameter passing methods

  • Pass-by-value
  • Pass-by-reference
  • Pass-by-result
  • Pass-by-value-result
  • Pass-by-name

program P; var I: Integer; A: array [ 1..3 ] of Integer; procedure Test ( F, G: Integer ); begin F := F + 1; G := 5 * I; end; begin for I := 1 to 3 do A [ I ] := I; I := 2; Test ( I, A [ I ] ); Write ( I, A [ 1 ], A [ 2 ], A [ 3 ] ); end. Imaginary language following Pascal syntax:

slide-9
SLIDE 9

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

9

Parameters passed by value

  • Passing information from the caller to the

subprogram

– formal parameter is like a local variable – initialized with the value of the actual parameter var F: Integer := I; = 2 G: Integer := A [ I ]; = A [ 2 ] = 2 begin F := F + 1; = 3 G := 5 * I; = 10 end; 2 1 2 3 Output:

? act.

slide-10
SLIDE 10

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

10

Parameters passed by reference

  • Passing information in both directions

– formal parameter refers to the variable (store, memory location) given in the call – variable (store) is defined before the call and remains the same throughout the execution – requires an actual parameter to be a variable (lvalue) begin I := I + 1; = 3 A [ 2 ] := 5 * I; = 15 end; 3 1 15 3 Output:

act.

slide-11
SLIDE 11

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

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 subprogram execution – formal parameter cannot be changed – (changes in actual parameter are visible in the subprogram) – good if copying values is costly (memory/time)

slide-12
SLIDE 12

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

12

Parameters passed by value-result

  • Passing information in both directions

– formal parameter is like a local variable – its initial value is the value of the actual parameter – final value is copied to the actual parameter var F: Integer := I; = 2 G: Integer := A [ 2 ]; = 2 begin F := F + 1; = 3 G := 5 * I; = 10

  • I := F;

= 3 A [ 2 ] := G; = 10 end; 3 1 10 3 Output:

act.

slide-13
SLIDE 13

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

13

Parameters passed by result

  • Passing information from the subprogram to the

caller

– formal parameter is like a local variable that has not yet initialized – final value is copied to the actual parameter var F, G: Integer; begin F := F + 1; G := 5 * I;

  • I := F;

A [ 2 ] := G; end; Execution leads to an error (in this example)

act. ? ”Multiple return values”

slide-14
SLIDE 14

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

14

Parameters passed by name

  • Textual copy
  • Actual parameter is evaluated each time it is

referenced in the subprogram

  • Variable names in the parameter expression refer to

the scope of the caller

  • C.f. lazy evaluation, lambdas, #define in C/C++

begin I := I + 1; = 3 A [ I ] := 5 * I; i.e. A [ 3 ] = 15 end; 3 1 2 15 Output:

In no major language any more (Algol60)

slide-15
SLIDE 15

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

15

Pass-by-name example

n

∑ E ( i )

i=p

function Sum ( i: name Integer; p, n: Integer; E: name Real ): Real; var S: Real := 0.0; begin for i := p to n do S := S + E; Sum := S; end; var x: Integer; r: Real; ... r := Sum ( x, 1, 100, 2 * Sin ( 3.14 * x ) – 3 * x );

Imaginary language following Pascal’s syntax:

slide-16
SLIDE 16

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

16

Parameter passing in programming languages

  • Java & Python

– pass-by-value (for primitive types) – pass-by-reference (for classes)

  • C

– pass-by-value (but arrays are passed by reference)

  • C++

– pass-by-value and pass-by-reference

  • Ada

– pass-by-value (in) [default passing method] – pass-by-result (out) – pass-by-value-result (in out)

  • Pascal

– pass-by-value (val) [default passing method] – pass-by-reference (var)

pass-by-name in Algol60

slide-17
SLIDE 17

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

17

Parameter passing in Haskell

  • Called pass-by-assignment

– actual parameter value is assigned to the formal parameter – lazyness: values are evaluated only when needed

  • In effect: pass-by-reference

– every variable is a reference to an object – therefore actual parameters are references

  • However: in most cases pass-by-value

– many objects are immutable – changing the formal parameter has no effect on the caller

  • E.g. passing a reference to an array

– no effect on the caller when the formal parameter is assigned a new array object – however, assigning a value to an element of the array, the actual parameter is affected

list [ 3 ] = 47

slide-18
SLIDE 18

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

18

Observations on parameter passing (side effects)

  • Side effect

– subprogram has a side effect, if it influences subsequent computation in any way other than by returning a value for use in the surrounding context

  • e.g. changing the value of a global variable
  • Function side effects are especially not desired

– restriction in Ada:

  • function parameters must be in-parameters
  • In general:

– subprogram changes the value of data that is declared outside the subprogram – this is normal in object-oriented programming: an operation in a class changes the value of an attribute in the class

a = 10; b = a + f ( a );

slide-19
SLIDE 19

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

19

Observations on parameter passing (aliasing)

  • Same memory location (variable) can be referenced

by multiple names

– makes program more difficult to understand – e.g. passing a global variable by reference var x: Integer; procedure P1 ( var y, z: Integer ); var a: Real; begin z := 0; y := 1; a := 1 / ( y – z ) end; ... P1 ( x, x );

  • Origins of aliasing:

– parameter passing – pointer variables division by zero

Pascal-code

slide-20
SLIDE 20

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

20

Multi-dimensional arrays as parameters (C)

void fun ( float matrix [ ] [ 10 ] ); void fun ( float *mat_ptr, int num_rows, int num_cols ); { /* assigning x to the index [ row ] [ col ] */ * ( mat_ptr + ( row * num_cols ) + col ) = x; ... } #define mat_ptr ( r, c ) ( * ( mat_ptr + ( ( r ) * num_cols ) + ( c ) ) ) ... mat_ptr ( row, col ) = x;

address ( mat [ i, j ] ) = address ( mat [ 0, 0 ] ) + i * num_cols + j

slide-21
SLIDE 21

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

21

Multi-dimensional arrays as parameters (Java)

float Sum ( float matrix [ ] [ ] ) { float sum = 0.0f; for ( int row = 0; row < matrix.length; row++ ) { for ( int col = 0; col < matrix [ row ].length; col++ ) { sum += matrix [ row ] [ col ]; } } return sum; }

slide-22
SLIDE 22

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

22

Subprograms as parameters

procedure proc ( i: Integer; procedure p; x: Real ); procedure proc ( i: Integer; procedure p (ch: Char, var i: Integer ); x: Real ); TYPE ProcType = PROCEDURE ( CHAR, VAR INTEGER ); PROCEDURE proc ( i: INTEGER; p: ProcType; x: REAL ); Pascal (1975) Pascal (ANSI) Modula-2

slide-23
SLIDE 23

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

23

Referencing environment (of subprogram parameters)

1. Shallow binding

  • the environment of the

subprogram that calls the passed subprogram

  • prints 4

2. Deep binding

  • the environment of the

definition of the passed subprogram

  • prints 1

3. Ad hoc binding

  • the environment of the call

that passed the subprogram as an actual parameter

  • prints 3

procedure Sub1; var x: Integer; procedure Sub2; begin write ( x ); end; procedure Sub3; var x: Integer; begin x := 3; Sub4 ( Sub2 ); end; procedure Sub4 ( SubX ); var x: Integer; begin x := 4; SubX; end; begin x := 1; Sub3; end; Imaginary language following Pascal syntax

slide-24
SLIDE 24

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

24

Subprogram overloading

  • Different subprograms have the same name

– besides the name, called subprogram can be identified by the number and types of parameters

  • Arithmetic operators (+, -, *, /) are overloaded

function Average ( i1, i2: Integer ) return Integer is begin return ( i1 + i2 ) / 2;

  • - integer division

end Average; function Average ( r1, r2: Float ) return Float is begin return ( r1 + r2 ) / 2.0;

  • - float division

end Average;

Ada:

slide-25
SLIDE 25

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

25

Overloading (Ada)

  • Simplified rule:

– from any identifier occurence, it must always be possible to conclude which (overloaded) identifier is referenced (meant)

  • Examples:

Overloadable:

  • subprograms
  • enumeration literals
  • ports

X: Integer; type T is ( X, ... ); procedure X ( A: Integer ) ... procedure X ( B: Positive ) ... type T is ( X, ... ); function X return T is ... function X return ... procedure X is ... type T is new Integer ...; procedure X ( A: Integer) ... procedure X ( B: T ) ... type T is ( X, ... ); procedure X is ... Illegal declarations: X: Integer; procedure X ( ... ); Legal declarations:

slide-26
SLIDE 26

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Name mangling

  • Compiler generates unique names for

programming entities

  • Needed in languages which enable operator
  • verloading, templates, classes,

namespaces, or case insensitive identifiers

  • Example in overloading (g++ compiler):

void myFun ( ); => _Z5myFunv void myFun ( int a, char c ); => _Z5myFunic

slide-27
SLIDE 27

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Name mangling (mixing C and C++)

#ifdef __cplusplus extern ”C” { #endif /* unmangled stuff */ #ifdef __cplusplus } #endif char *strcat ( char *, const char * ); int strcmp ( const char *, const char * ); char *strcpy ( char *, const char * );

slide-28
SLIDE 28

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

28

Subprogram memory management (implementation)

  • Static allocation (e.g. Fortran)

– for each variable, memory is allocated at compile time – wasteful (subprograms are not necessarily called) – recursion is impossible – may lead to bad programming style (using the local values assigned in the previous call)

  • Dynamic allocation (modern languages)

– subprogram call creates an activation record – memory is allocated from the stack – memory is allocated when needed (called)

slide-29
SLIDE 29

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

29

Subprogram implementation (simple cases)

  • Subprogram call

1. Pass the return address to the called subprogram (PC + 1) 2. Pass the actual parameters 3. Move control to the called subprogram 4. Store the local variables to their locations

  • Subprogram return

1. Put function result to its location 2. Move parameter values to actual parameters (if parameters are passed by value-result or by result) 3. Restore the run time situation of the caller (return address) 4. Move control back to caller Function result Parameters Return address Local variables Activation record (stack frame):

slide-30
SLIDE 30

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

30

More complicated subprograms

  • Enabling recursion

– program counter (PC) is not sufficient – dynamic link is needed to point to the activation record of the caller

  • Enabling nested subprograms

– static link is needed to point to the next outer level subprogram (outer scope)

  • subprogram execution (e.g. Outer) cannot terminate

before all subprograms activated by it (e.g. Inner) have terminated

  • a subprogram can activate only those subprograms

that are visible to it

proc Outer proc Inner begin ... end Inner; begin Inner ( ); ... end Outer; Imaginary language: The link is always found because

slide-31
SLIDE 31

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

31

Content of activation record

  • Return address

– at calling moment: PC + 1

  • Static link (access link)

– points to the activation record of the next outer scope

  • Dynamic link (control link)

– the former stack top or the link to the activation record of the caller

  • Actual parameters

– passed-by-value: like local variables – passed-by-reference: space for a memory address

  • Local variables

– in addition, potential temporary variables (created by the compiler)

  • Function result

Function result Local variables Parameters Static link Dynamic link Return address

slide-32
SLIDE 32

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

32

Static and dynamic environment

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

dynamic link static link

D ...

dynamic link static link

C ...

dynamic link static link

A ...

dynamic link static link

Activation record stack at <point2>?

slide-33
SLIDE 33

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

33

Display tables

  • Finding non-local identifiers

– size of the display is the same as the maximum nesting depth – index i contains pointer to the latest activation at depth i – display is updated in subprogram calls and returns

  • Finding a variable at depth i

– activation record from Display [ i ] – final address is evaluated ( Display [ i ] + offset ) inner main

  • uter

Activation record stack

2 1

Display table

slide-34
SLIDE 34

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

34

Display example

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

d [ 3 ] d [ 2 ] d [ 1 ] d [ 3 ] d [ 2 ] d [ 1 ]

At <point1>? At <point2>?

slide-35
SLIDE 35

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

35

Recursive subprograms

  • Recursion

– a single subprogram has several activations (activation records) in the activation record stack

  • Terminology for recursive subprograms:

– direct recursion

  • subprogram calls itself

– indirect recursion

  • recursive call via another subprogram (A calls B, and B calls A)

– linear recursion

  • subprogram calls itself once at one execution of the subprogram

– tail recursion

  • linear recursion such that the recursive call is the last executed

command of the subprogam

slide-36
SLIDE 36

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

36

Elimination of tail recursion

  • Caller removes from the stack the parameters it

has received (return address is left untouch)

  • Caller puts new parameters (that are needed by the

callee) onto the stack

  • Execution of the called subprogram is started

int gcd ( int a, int b ) { if ( a == b ) return a; else if ( a > b ) return gcd ( a – b, b ); else return gcd ( a, b – a ); } int gcd ( int a, int b ) { start: if ( a == b ) return a; else if ( a > b ) { a = a – b; goto start; } else { b = b – a; goto start; } }

  • ptimize

C:

slide-37
SLIDE 37

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

37

Blocks

  • Can be implemented like nested subprograms

– parameterless subprograms – always called in the same place

  • Implementation can be simplified

– the required memory for the local variables of the block is statically determined – blocks are entered and exited in strictly textual order – memory for the block variables can be allocated after the local variables of the outer scope in the activation record

slide-38
SLIDE 38

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

38

Block implementation

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

main ... ... ... x d c b / g a / f z y e block variables local variables

  • f main
slide-39
SLIDE 39

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Implementation of lambdas

  • Lambdas are nameless functions…
  • …but can refer to the variables of the scope where

they were created: not quite functions

  • When a lambda expression is evaluated, a closure

is produced

  • Closure contains the lambda’s code (function) and

a reference to the lambda’s creation environment

  • Environment reference: pointers to used variables
  • nly or to the entire activation record
slide-40
SLIDE 40

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Implementation of lambdas (C++)

  • Compiler creates a small functor class from

a lambda

  • The class overloads operator()
  • Variables in the surrounding environment
  • f the lambda are passed into the

constructor of the class and saved as member variables

slide-41
SLIDE 41

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

No variables captured

[ ] ( X& elem ) { elem.op(); } class _genName_ { public: void operator() ( X& elem ) const { elem.op( ); } }; generated as

slide-42
SLIDE 42

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Variables captured

[ &total, offset ] ( X& elem ) { total += elem.getVal ( ) + offset; } class _genName_ { public: _genName_ ( int& t, int o ) : total_{ t }, offset_ { o } { } void operator ( ) ( X& elem ) const { total_ += elem.getVal ( ) + offset_; } private: int& total_; // context captured by reference int offset_; // context captured by value }; generated as