Parameter Passing Protocols COSC 341 28 November 2017 Call-by-value Upon entry, copy actual parameter value into formal (passing value) parameter location Call-by-value-result Upon entry, copy actual parameter value into formal (passing value) parameter location; Upon exit, copy format parameter value into actual parameter location. Call-by-reference Upon entry: formal parameter is a new name (i.e., alias) (passing address) for actual parameter. Call-by-name Upon entry: formal parameter text is replaced by (textual substitution) actual parameter text. EXAMPLES (1) Ex 9.11 (from Scott, *Programming Languages Pragmatics*) referencing environment x y x: integer - proc foo (y: integer) | - y := 3 | | print x | | end foo | - . . . | x := 2 | foo(x) | print x | . . . - Output for each protocol: call-by-value:: 2 2 call-by-value-result: 2 3 call-by-reference: 3 3 call-by-name: 3 3 (2) Swap main() { x = 3 y = 2 swap(x, y) print "main: ", x, y } swap(a, b) { t = a a = b b = t print "swap: ", a, b } Output for each protocol: call-by-value:: swap: 2 3 main: 3 2 call-by-value-result: swap: 2 3 main: 2 3 call-by-reference: swap: 2 3 main: 2 3 call-by-name: swap: 2 3 main: 2 3 (3) Swap -- different example using array int i int v[] = {3, 2, 1, 0} main() { i = 0 swap(i, v[i]) print "main: ", i, v[i] } swap(a, b) { t = a a = b b = t print "swap: ", a, b } Output for each protocol: call-by-value:: swap: 3 0 main: 0 3 3 2 1 0 call-by-value-result: swap: 3 0 main: 3 0 0 2 1 0 call-by-reference: swap: 3 0 main: 2 3 0 0 2 1 0 call-by-name: swap: 2 3 main: 2 3 3 2 1 0 (4) Jensen's Device int i, j, m, n int v[] = {10, 20, 30} int A[][] = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8}} addUp(k, l, u, ak) { s = 0 for (k= l; k <= u; k++) { s = s + ak } print s } main() { addUp(i, 0, 2, i); // 0 + 1 + 2 addUp(i, 0, 2, (i*i)); // (0*0) + (1*1) + (2*2) addUp(i, 0, 2, v[i]); // v[0] + v[1] + v[2] m = 2; n = 2; addUp(i, 0, m, addUp(j, 0, n A[i][j])); // // }