Oct 22, 2003 ------------- - Uses of guarded commands - guarded if to find max of two integers - guarded do to sort a bunch of integers - Move on to next chapter - subprograms - What is a procedure? - a block whose declaration is separated from its execution - What is a function? - a procedure which returns a value - Thinking of procedures - as a means of one segment of program to communicate with another - Consider the code segment program ... var i: integer; procedure a; begin i := 2; end; procedure b; var i: integer; begin i := 3; a; end; begin b; end. - How can one block of code "communicate" with another? - the i in "a" is the i of the main program - how can "b" send its value of i to "a"? - Two approaches - use dynamic scoping - with static scoping, use parameter passing - Simplest parameter passing strategy - pass by value - use a(i : integer) and call as a(i) in b - Another parameter passing approach - pass by reference - use a(var i: integer) - Languages and their strategies - Pascal supports both - C only has pass by value - have to fake pass by reference by sending pointers by value - Other approaches - pass by value-result - pass by result - pass by name - A simple way to think about each of them - pass by value - IN - pass by reference - IN-OUT - pass by value-result - IN up at the front - OUT at the back - pass by result - OUT - pass by name - lazy evaluation - akin to #define in C - Sample code snippets for each of the above: - note: Pascal style code is used only for illustration, it is not that Pascal uses these mechanisms Pass by value-result --------------------- (* answer is 2, if value-result is used; answer is 3, if reference is used *) procedure p(x,y: integer); begin x := x + 1; y := y + 1; end; begin a := 1; p(a,a); (* what value is a here? *) end. Pass by name: -------------- (* basically has the effect of doing a[i] := a[i] + 1 *) procedure p(x); begin x := x +1; end; p(a[i]); Another pass by name: --------------------- (* sets a[2] to 3, and leaves a[1] unchanged *) var i: integer; a: array [1..10] of integer; procedure p(x); begin i := i+1; x : = x+1; end; begin i := 1; a[1] := 1; a[2] := 2; p(a[i]); end. Yet Another pass by name: ------------------------- (* program will print 5 *) program test; var i : integer; function p(y: integer) : integer; var j : integer; begin j := y; i := i +1; p := j + y; end; procedure q; var j : integer; begin i := 0; j := 2; writeln(p(i+j)); end; begin q; end. Use of pass by name: -------------------- (* called Jensen's device *) function sum(a, index, lower, uppper: integer) : integer; var temp: integer begin temp := 0; for index := lower to upper do temp := temp + a; sum := temp; end; var x: array[1..10] of integer; i, xtotal: integer; xtotal := sum(x[i], i, 1, 10);