COP4020 Programmig Laguages Subrouties ad Parameter Passig Prof. Robert va Egele
Overview Parameter passig modes Subroutie closures as parameters Special-purpose parameters Fuctio returs COP4020 Fall 2016 2
Parameters First some defiitios Formal parameters Lisp: (lambda (a b) (/ (+ a b))) C fuctio: float ave(float a, float b) { retur (a+b)/2.0; } Versus actual parameters Lisp fuctio argumets: (ave x 10.0) C fuctio argumets: ave(x, 10.0) Versus operads (of operators ad special forms) Lisp special forms: (if flag yes o ) C operators: x > 0 && flag Operad hadlig ofte depeds o the type of built-i operator, e.g. special forms ad operators with short-circuit evaluatio COP4020 Fall 2016 3
Parameter Passig Parameter passig modes I I/out Out Parameter passig mechaisms Call by value (i) Call by referece (i+out) Call by result (out) Call by value/result (i+out) Call by ame (i+out) Differet mechaisms used by C, Fortra, Pascal, C++, Java, Ada (ad Algol 60) COP4020 Fall 2016 4
Parameter Passig i C Call by value parameter passig oly Actual parameter is evaluated ad its value assiged to the formal parameter A formal parameter i the fuctio body behaves as a local variable For example: it fac(it ) { if ( < 0) = 0; retur? *fac(-1) : 1; } Passig poiters allows the values of actuals to be modified For example: swap(it *a, it *b) { it t = *a; *a = *b; *b = t; } A fuctio call should explicitly pass poiters, e.g. swap(&x, &y); Arrays ad poiters are exchageable i C A array is automatically passed as a poiter to the array COP4020 Fall 2016 5
Parameter Passig i Fortra Call by referece parameter passig oly If the actual parameter is a l-value (e.g. a variable) its referece is passed to the subroutie If the actual parameter is a r-value (e.g. the value of a expressio) it is assiged to a hidde temporary variable whose referece is passed to the subroutie For example SUBROUTINE SHIFT(A, B, C) INTEGER A, B, C A = B B = C END For example, SHIFT(X, Y, 0) assigs Y to X, ad Y is set to 0 For example, SHIFT(X, 2, 3) assigs 2 to X ad the assigmet to B i the subroutie has o effect, but i Fortra IV this was ot hadled correctly! COP4020 Fall 2016 6
Parameter Passig i Pascal Call by value ad call by referece parameter passig Call by value is similar to C Call by referece: idicated with var qualifier i argumet list For example procedure swap(var a:iteger, var b:iteger) var t; begi t := a; a := b; b := t ed where the var parameters a ad b are passed by referece Programs ca suffer from uecessary data duplicatio overhead Whe a big array is passed by value the etire array is copied! Passig large arrays by referece avoids copy overhead But o clear distictio betwee i-mode or i/out-mode ay loger COP4020 Fall 2016 7
Parameter Passig i C++ Call by value ad call by referece parameter passig Call by value is similar to C Call by referece: use referece (&) operator For example: swap(it &a, it &b) { it t = a; a = b; b = t; } where the referece parameters a ad b are passed by referece Arrays are automatically passed by referece (like i C) Big objects should be passed by referece istead of by value To protect data from modificatio whe passed by referece, use cost, i.e. make it a i-mode parameter For example: store_record_i_file(cost huge_record &r) {... } Compiler will prohibit modificatios of object cost parameters (e.g. poiters) are also supported i ANSI C COP4020 Fall 2016 8
Parameter Passig by Sharig Call by sharig: parameter passig of variables i the referece model Referece model: variables are refereces to (shared) values Smalltalk, Lisp, ML, Clu, ad Java (partly) adopt the referece model of variables The value of the variable is passed as actual argumet, which i fact is a poiter to the (shared) value Essetially this is pass by value of the variable! Java uses both pass by value ad pass by sharig Variables of primitive built-i types are passed by value Class istaces are passed by sharig COP4020 Fall 2016 9
Parameter Passig i Ada I-mode parameters ca be read but ot writte i the subroutie Call by value Out-mode parameters ca be writte but ot read i the subroutie (Ada 95 allows read) Call by result, which uses a local variable to which the writes are made The resultig value is copied to the actual parameter to pass the value out whe the subroutie returs I-out-mode parameters ca be read ad writte i the subroutie Call by value/result uses a local variable that is iitialized by assigig the actual parameter's value to it The resultig value is copied to the actual parameter to pass the value out whe the subroutie returs Call by value, call by result, ad call by value/result parameter passig implemets i, out, ad i/out parameters, respectively Dager ahead: may use call by referece implemetatio for passig oscalars i/out (e.g. records ad arrays) to avoid copyig large objects! COP4020 Fall 2016 10
Parameter Passig i Ada: Example For example procedure shift(a:out iteger, b:i out iteger, c:i iteger) is begi a := b; b := c; ed shift; Here, a is passed out, b is passed i ad out, ad c is passed i COP4020 Fall 2016 11
Parameter Passig i Ada (cot d) The Ada compiler geerates specific code for the example shift procedure for i, out, ad i/out parameters to implemet call by value (i), call by result (out), ad call by value/result (i/out), which is similar to the followig C fuctio: void shift(it *a, it *b, it c) { it tmpa, tmpb = *b, tmpc = c; // copy iput values at begi } tmpa = tmpb; tmpb = tmpc; // perform operatios o temps *a = tmpa; *b = tmpb; // copy result values out before retur Temps are iitialized, operated o, ad copied to out mode parameters This is more efficiet tha pass by referece, because it avoids repeated poiter idirectio to access parameter values The Ada compiler may decide to use call by referece for passig oscalars (e.g. records ad arrays) for memory access optimizatio Okay for i-mode, because the parameter may ot be writte Okay for out ad i-out modes, sice the parameter is writte ayway COP4020 Fall 2016 12
Parameter Passig ad Aliasig A alias is a variable or formal parameter that refers to the same value as aother variable or formal parameter Example variable aliases i C++: it i, &j = i; // j refers to i (is a alias for i) i = 2; j = 3; cout << i; // prits 3 Example parameter aliases i C++: shift(it &a, it &b, cost it &c) { a = b; b = c; } The result of shift(x, y, x) is that x is set to y but y is uchaged Example mixig of variable ad parameter aliases i C++: it sum = 0; score(it &total, it val) { sum += val; total += val; } The result of score(sum, 7) is that sum is icremeted by 14 COP4020 Fall 2016 13
Parameter Passig ad Aliasig (cot d) Java adopts referece model of variables ad call by sharig Watch out for aliases, sice i referece model all assigmets create aliases Ada forbids parameter aliases Allows compiler to choose call by referece with the same effect as call by result But most compilers do t check ad the resultig program behavior is udefied COP4020 Fall 2016 14
Parameter Passig i Algol 60 Call by ame parameter passig by default, also call by value Passes actual argumets such as expressios ito the subroutie body for (re)evaluatio (reevaluatio doe via code thuks ) Jese's device utilizes call by ame: real procedure sum(expr, i, low, high); value low, high; low ad high are passed by value real expr; expr ad i are passed by ame iteger i, low, high; begi real rt; rt := 0; for i := low step 1 util high do rt := rt + expr; sum := rt ed sum the value of expr depeds o the value of i retur value by assigig to fuctio ame y := sum(3*x*x-5*x+2, x, 1, 10) calculates 10 y = Σ 3x 2-5x+2 x=1 COP4020 Fall 2016 15
Macro Expasio C/C++ macros (also called defies) adopt a form of call by ame For example #defie max(a,b) ( (a)>(b)? (a) : (b) ) Macro expasio is applied to the program source text ad amouts to the substitutio of the formal parameters with the actual parameters i the macro For example max(+1, m) is replaced by ((+1)>(m)?(+1):(m)) Note: formal parameters are ofte parethesized to avoid sytax problems whe expadig Similar to call by ame, actual parameters are re-evaluated each time the formal parameter is used Watch out for re-evaluatio of fuctio calls i actual parameters, for example max(somefuc(),0) results i the evaluatio of somefuc() twice if it returs a value >0 COP4020 Fall 2016 16
Parameter Passig Issues Call by ame problem: hard to write a swap routie that works: procedure swap(a, b) iteger a, b, t; begi t := a; a := b; b := t ed swap Cosider swap(i, a[i]), which executes: t := i i := a[i] this chages i a[i] := t assigs t to wrog array elemet COP4020 Fall 2016 17
Parameter Passig Issue (cot d) Call by value/result problem: behaves differetly compared to call by referece i the presece of aliases (that s why Ada forbids it) For example: procedure shift(a:out iteger, b:i out iteger, c:i iteger) is begi a := b; b := c; ed shift; Whe shift(x,x,0) is called by referece the resultig value of x is 0 Whe shift(x,x,0) is called by value/result the resultig value of x is either uchaged or 0 (because the order of copyig out mode parameters is uspecified) COP4020 Fall 2016 18
Coformat Arrays Some laguages support coformat arrays (or ope arrays) Examples: Ada, Stadard Pascal, Modula-2 Pascal arrays are types with embedded costat array bouds Arrays have fixed shape ad size Problem whe for example sortig arrays of differet sizes because sort procedure accepts oe type of array with oe size oly Array parameters i Stadard Pascal are coformat ad array size is ot fixed at compile-time For example: fuctio sum(a : array[low..high : iteger] of real) : real... Fuctio sum accepts real typed arrays ad low ad high act like formal parameters that are set to the lower ad upper boud idex of the actual array parameter C passes oly poiters to arrays to fuctios ad array size has to be determied usig some other meas (e.g. as aother parameter) COP4020 Fall 2016 19
Closures as Parameters Recall that a subroutie closure is a referece to a subroutie together with its referecig eviromet Stadard Pascal, Ada 95, Modula-2+3 fully support passig of subrouties as closures Stadard Pascal example: procedure apply_to_a(fuctio f(:iteger) : iteger; var A : array [low..high : iteger] of iteger); var i : iteger; begi for i := low to high do A[i] := f(a[i]) ed C/C++ supports fuctio poiters ad lambdas (C++11) Lambdas ca capture a referece eviromet Fuctio poiters are simplistic, for example: void apply_to_a(it (*f)(it), it A[], it A_size) { it i; for (i = 0; i < A_size; i++) A[i] = f(a[i]); } COP4020 Fall 2016 20
Default Parameters Ada, C++, Commo Lisp, ad Fortra 90 support default parameters A default parameter is a formal parameter with a default value Whe the actual parameter value is omitted i a subroutie call, the user-specified default value is used Example i C++: void prit_um(it, it base = 10)... A call to prit_um(35) uses default value 10 for base as if prit_um(35,10) was called Example i Ada: procedure put(item : i iteger; width : i field := default_width; base : i umber_base := 10) is... A call to put(35) uses default values for the width ad base parameters COP4020 Fall 2016 21
Positioal Versus Named Parameters Positioal parameters: the order of formal ad actual argumets is fixed All programmig laguages adopt this atural covetio Named parameter: (also called keyword parameter) explicitly bids the actual parameter to the formal parameter Ada, Modula-3, Commo Lisp, ad Fortra 90 For example i Ada: put(item => 35, base => 8); this "assigs" 35 to item ad 8 to base, which is the same as: put(base => 8, item => 35); ad we ca mix positioal ad ame parameters as well: put(35, base => 8); Pro: documetatio of parameter purpose Pro: allows default parameters aywhere i formal parameter list, whereas with positioal parameters the use of default parameters is restricted to the last parameter(s) oly, because the compiler caot tell which parameter is optioal i a subroutie ivocatio COP4020 Fall 2016 22
Variable Argumet Lists C,C++, ad Commo Lisp are uusual i that they allow defiig subrouties that take a variable umber of argumets Example i C: #iclude <stdarg.h> it plus(it um,...) { it sum; va_list args; // declare list of argumets va_start(args, um); // iitialize list of argumets for (it i=0; i<um; i++) sum += va_arg(args, it); // get ext argumet (assumed to be it) va_ed(args); // clea up list of argumets retur sum; } Fuctio plus adds a set of itegers, where the umber of itegers is the first parameter to the fuctio: plus(4,3,2,1,4) is 10 Used i the pritf ad scaf text formattig fuctios i C Variable umber of argumets i C ad C++ is ot type safe as parameter types are ot checked I Commo Lisp, oe ca write (+ 3 2 1 4) to add the itegers COP4020 Fall 2016 23
Fuctio Returs Some programmig laguages allow a fuctio to retur ay type of data structure, except maybe a subroutie (requires first-class subrouties) Modula-3 ad Ada allow a fuctio to retur a subroutie as a closure C ad C++ allow fuctios to retur poiters to fuctios (o closures) Some laguages use special variable to hold fuctio retur value Example i Pascal: fuctio max(a : iteger; b : iteger) : iteger; begi if a>b the max := a else max := b ed There is o retur statemet, istead the fuctio returs with the value of max whe it reaches the ed The subroutie frame reserves a slot for the retur value ayway, so these laguages make the slot explicitly available COP4020 Fall 2016 24
Fuctio Returs (cot d) Ada, C, C++, Java, ad other more moder laguages typically use a explicit retur statemet to retur a value from a fuctio Example i C: it max(it a, it b) { if (a>b) retur a; else retur b; } Programmers may eed a temporary variable for icremetal operatios o the retur value For example: it fac(it ) { it ret = 1; for (i = 2; i <= ; i++) ret *= i; retur ret; } Wastes time copyig the temporary variable value ito retur slot of subroutie frame o the stack COP4020 Fall 2016 25