1.23k likes | 1.26k Views
Chapter 9 Subprograms. CS 350 Programming Language Design Indiana University – Purdue University Fort Wayne. Chapter 9 topics. Fundamentals of subprograms Design issues for subprograms Local referencing environments Parameter-passing methods Parameters that are subprograms
E N D
Chapter 9Subprograms CS 350 Programming Language Design Indiana University – Purdue University Fort Wayne
Chapter 9 topics • Fundamentals of subprograms • Design issues for subprograms • Local referencing environments • Parameter-passing methods • Parameters that are subprograms • Overloaded subprograms • Generic subprograms • Design issues for functions • User-defined overloaded operators • Co-routines • Calling Subprograms Indirectly • Closures
Introduction • There are two fundamental abstraction facilities in programming languages • Process abstraction (Chapter 9 and Chapter 10) • Data abstraction (ADTs) (Chapter 11) • Historically, process abstraction matured first • Process abstraction, in the form of subprograms, has been a central concept in all programming languages.
Introduction • Two fundamental abstraction facilities in programming languages • Process abstraction • Data abstraction (ADTs) • … • Process abstraction begun since 1980. . . • Promotes reuse of collection of statements which is written as a subprogram. • Separates WHAT a subprogram does from HOW it does
ADT • The product of data abstraction is an abstract data type (ADT). In object-oriented languages (like Java), ADT's are implemented as classes • An abstract data type (ADT) consists of: • An interface -- a set of operations that can be performed (also known as an abstraction barrier). • Allowable behaviors -- the way we expect instances of the ADT to respond to operations. • The implementation of an ADT consists of: • An internal representation – data (variables) stored inside the object's instance • A set of methods implementing the interface • A set of representation invariants, and preserved by all methods
Fundamentals of subprograms • General characteristics of subprograms • A subprogram has a single entry point • The calling program is suspended during execution of the called subprogram • There is only one subprogram in execution at any given time • Control always returns to the caller when the called subprogram’s execution terminates
Fundamentals of subprogramsA subprogram call Caller (the calling program) Callee (the called subprogram)
Fundamentals of subprograms • Basic definitions • A subprogram call • is an explicit request that a specific subprogram be executed • A subprogram definition • describes the interfaceand the actions of the subprogram abstraction • A subprogram is said to be active • if, after having been called, it has begun execution but has not completed that execution.
Fundamentals of subprograms • Basic definitions • A subprogramheader is the first part of the definition • Name of subprogram • Type of subprogram – procedure or function • Formal parameters • Example of the header of a function named adder in C: voidadder (parameters) • The reserved word void in this header indicates that the subprogram does not return a value. • The body of subprograms defines its actions. • The body of a subprogram is delimited by braces in the C-based languages. In Ruby, an end is used.
Fundamentals of subprograms • Basic definitions • The parameter profile (or signature) of a subprogram is • the number, order and types of its formal parameters • The protocol of a subprogram is • its parameter profile plus, if it is a function, its return value and return type
Fundamentals of subprograms • Basic definitions (continued) • A subprogram declaration provides the protocol, but not the body, of the subprogram • C, C++, and Ada permit separate declarations • Allows compiler to check protocols before bodies are written • intcalculate_bill (int, int, int); … bill = calculate_bill (john, jane, kevin) //call statement • A formal parameter(in a called subprogram header) • An actual parameter (in a calling statement)
Fundamentals of subprograms • Basic definitions (continued) • A subprogram declaration • A formal parameter is a dummy variable listed in the subprogram header and used in the subprogram • These variables are bound to storage only when the subprogram is called, and that binding is often through some other program variables • An actual parameter represents a value or address used in the subprogram call statement
Fundamentals of subprograms • Basic definitions (continued) • A subprogram declaration • A formal parameter • An actual parameter represents a value or address used in the subprogram call statement • Subprogram call statements include the subprogram name and a list of parameters to be bound to the formal parameters of the subprogram. These parameters are called actual parameters.
Fundamentals of subprograms #include <stdio.h> int main (void); intcalculate_bill (int, int, int); int main() { int bill; intfred = 25; int frank = 32; intfranny = 27; bill = calculate_bill (fred, frank, franny); printf("The total bill comes to $%d.00.\n", bill); exit (0); } intcalculate_bill (int diner1, int diner2, int diner3) { int total; total = diner1 + diner2 + diner3; return total; } • Basic definitions (continued) • A subprogram declaration provides the protocol, but not the body, of the subprogram • C, C++, and Ada permit separate declarations • Allows compiler to check protocols before bodies are written • A formal parameter is a dummy variable listed in the subprogram header and used in the subprogram • An actual parameter represents a value or address used in the subprogram call statement Actual Parameters Formal Parameters
Fundamentals of subprograms • Correspondence between actual & formal parameters – the binding of actual parameters to formal parameters • Positional correspondence • First actual parameter is bound to the first formal parameter • Keyword correspondence • Example Search( List => MyList, Start => 100, Finish => 200, Sum => MySum ); -------------------------------------------------------------------- Search( Sum => MySum, Start => 100, Finish => 200, List => MyList );
Fundamentals of subprograms • Correspondence between actual & formal parameters – the binding of actual parameters to formal parameters • Positional correspondence • Keyword correspondence • Example: the call statement can be • The name of the formal parameter to which an actual parameter is to be bound is specified with the actual parameter in a call. • The definition of Search has the (names of the) formal parameters List, Start, Finish, and Sum Search( List => MyList, Start => 100, Finish => 200, Sum => MySum ); -------------------------------------------------------------------- Search( Sum => MySum, Start => 100, Finish => 200, List => MyList );
Fundamentals of subprograms • Correspondence between actual & formal parameters – Disadvantages for these methods: • Positional correspondence • An effective and safe method of relating actual parameters to their corresponding formal parameters, as long as the parameter lists are relatively short. • Keyword correspondence • The user of the subprogram must know the names of formal parameters. • After a keyword parameter appears in the list, all remaining parmeters must be keyworded
Fundamentals of subprograms • Default values for formal parameters in Ada • A default value, such as “1” is used if no actual parameter is passed to the formal parameter “Exemptions” in the subprogram header. • After a default parameter is omitted, the remaining parameters must be passed by keyword correspondence functionComputePay( Income : Float; Exemptions : Integer := 1; -- a default value TaxRate : Float ) returnFloat; ------------------------------------------------- Pay := ComputePay( 20000.0, TaxRate => 0.15 );
Fundamentals of subprograms • C# allows certain methods to have a variable number of parameters • But, the parameters must be of the same type class TestParams { private static void Average(string title, paramsint[] values) { int sum = 0; System.Console.Write("Average of {0} (", title); for (inti = 0; i < values.Length; i++) { sum += values[i]; System.Console.Write(values[i] + ", "); } System.Console.WriteLine("): {0}", (float)sum/values.Length); } static void Main() { Average ("List One", 5, 10, 15); Average ("List Two", 5, 10, 15, 20, 25, 30); } }
Fundamentals of subprograms • C# allows certain methods to accept a variable number of parameters of the same type • The method specifies its formal parameter with the params modifier. • The call sends either an array or a list of expressions who values are placed in an array by the compiler and provided to the called method. class TestParams { private static void Average(string title, paramsint[] values) { int sum = 0; System.Console.Write("Average of {0} (", title); for (inti = 0; i < values.Length; i++) { sum += values[i]; System.Console.Write(values[i] + ", "); } System.Console.WriteLine("): {0}", (float)sum/values.Length); } static void Main() { Average ("List One", 5, 10, 15); Average ("List Two", 5, 10, 15, 20, 25, 30); } }
Fundamentals of subprograms • There are two categories of subprograms • Procedures provide parameterized computations • They do not return values • Functionsare modeled on mathematical functions • They return values • They can be used as procedures, if they defined not to return values • In C-based languages, void functions behave like procedures
Fundamentals of subprograms • There are two categories of subprograms • Procedures provide parameterized computations • Procedures define new statements • If a language does not have a sort statement, a user can build a procedure to sort arrays of data and use a call to that procedure in place of the unavailable sort statement. Only some older languages, Fortran and Ada support procedures. • Procedures usually produce side effects without return value • Transmit results back to the caller through parameters • Parameter side effects are obvious and should not cause errors • Change non-local variables • Poor practice, except for instance variables in OOP
Fundamentals of subprograms • There are two categories of subprograms • Procedures • Functionsare modeled on mathematical functions • Functions are called by appearing in an expression • In C++ float power(float base, float exp) { … } //a function, power, that returns the value result = 3.4 * power (10.0, x) /* the func called by name, power, with the required actual parameter*/ • Functions return a value • The value replaces the call in the expression • Functions should produce no side effects • i.e., it modifies neither its parameters nor any variables defined outside the function • Except instance variables in object-oriented languages
Design issues for subprograms • What is the local referencing environment? • What parameter passing methods are used? • Are parameter types checked? • Are local variables static or dynamic? • Can subprogram definitions appear in other subprogram definitions (nesting)? • Can subprograms be passed as parameters? • If so, what is the referencing environment of a passed subprogram? • Can subprograms be overloaded? • Are subprograms allowed to be generic?
Local referencing environments • Local variables within a subprogram define a local reverencing environment • Their scope is usually the body of the subprogram in which they are defined. • They can be either static or stack dynamic • Local variables are usually stack-dynamic
Local referencing environments • In C and C++ functions, locals variables are stack dynamic by default, unless specifically declared to be static. • In the following C (or C++) function subprogram, • the variable sum is static and • count is stack dynamic int adder (int list[ ], intlistlen) { static intsum = 0; int count; for (count = 0; count < listlen; count++) sum += list [count]; return sum:
Local referencing environments • Local variables are usually stack-dynamic • They are bound to storage when the subprogram begins execution and are unbound from storage when that execution terminates. • Advantages of stack-dynamic local variables • Support recursion – It is essential that recursive subprogram have stack-dynamic local variables. • Sharing storage for local variables between an active subprogram and all inactive subprograms • Disadvantages • Allocation and de-allocation time for each call to the subprogram • Accesses to stack-dynamic local variables must be indirect. Indirect addressing is slow
Local referencing environments • Advantage of static local variables over stack-dynamic local variables • They requires no run-time overhead for allocation and deallocation. They are slightly more efficient. • If accessed directly, these accesses are more efficient. • They allow subprograms to be history sensitive vs the stack-dynamic local variables cannot be history sensitive (i.e., the stack-dynamic local variables cannot retain data values of local variable between calls.) • Disadvantages of static local variables • their inability to support recursion. • Their storage cannot be shared with the local variables of other inactive subprograms.
Local referencing environments • In C and C++ functions, locals variables are stack dynamic by default, unless specifically declared to be static. • In the following C (or C++) function subprogram, • the variable sum is static and • count is stack dynamic int adder (int list[ ], intlistlen) { static intsum = 0; int count; for (count = 0; count < listlen; count++) sum += list [count]; return sum:
Local referencing environments • The methods of C++, Java and C# have only stack-dynamic local variables. • In Python, the only declaration used in method definitions are for globals. • Any variable declared to be global in a method must be a variable defined outside the method. • A variable defined outside the method can be referenced in the method without declaring it to be global, but such a variable cannot be assigned in the method. • If the name of a global variable is assigned in a method, it is implicitly declared to be a local and the assignment does not disturb the global. • All local variables in methods are stack dynamic.
Parameter-passing methods • Parameter-passing methods are the ways in which parameters are transmitted to and/or from called subprogram. Let consider • The different semantics models of parameter-passing methods • The various implementation models invented by language designers for these semantics • The design choices of several languages and the methods used to implement the implementation models • The design considerations that face a language designer in choosing among the methods.
Parameter-passing methods • Parameter-passing methods are the ways in which parameters are transmitted to and/or from called subprogram. Let recognize • Caller call Callee Calling program unit Called subprogram … Sub(a, b, c) void Sub(int x, int y, int z) {…} … Actual parameters Formal parameters
Parameter-passing methodsSemantic Models of Parameter Passing • The different semantics models of parameter-passing methods • Formal parameters are characterized by one of three distinct semantics models • They can receive data from the corresponding actual parameter (called in mode model) • They can transmit data to the actual parameter (called out mode model) • They can do both (call inout mode model)
Parameter-passing methodsSemantic Models of Parameter Passing • There are three semantic models for parameter passing • in mode • Data may only be read from the actual parameter • The formal parameter may even be “read only” • out mode • Data may only be written to the actual parameter • The formal parameter may even be “write only” • inout mode • Both in mode and out mode • There are two conceptual models of passing parameters • Physically copy the values • Using the pointers
Parameter-passing methodsSemanticModels of Parameter Passing • There are two conceptual models of passing parameters – of how data transfers take place in parameter transmission: • Physically copy the values • An actual value is copied (to the caller, to the called, or both ways) or • Using the pointers • an access path is transmitted • Most commonly, the access path is a simple pointer or reference.
Parameter-passing methodsThree semantics models of parameter passing when physical moves are used
Parameter-passing methods Implementation models of parameter passing • Let consider the implementation models for the three semantics models of parameter passing. That is, the implementation of the three basic parameter transmission modes (namely, in mode, out mode, and inout mode) • When a parameter is: • Pass-by-Value (in mode) • Pass-by-Result (out mode) • Pass-by-Value-Result (inout mode) • Pass-by-Reference (inout mode) • Pass-by-Name
Parameter-passing methods Implementation models of parameter passing Semantic Model of Parameter-Passing In mode Out mode Inout mode • Let consider the implementation models for the three semantics models of parameter passing. That is, the implementation of the three basic parameter transmission modes (namely, in mode, out mode, and inout mode) • When a parameter is: • Pass-by-Value (in mode) • Pass-by-Result (out mode) • Pass-by-Value-Result (inout mode) • Pass-by-Reference (inout mode) • Pass-by-Name Pass-by-Value Pass-by-Value-Result Pass-by-Reference - Semantics of these two impl. models are the same Pass-by-Result
Parameter-passing methods Implementation models of parameter passing • Pass-by-value (inmode) • When a parameter is passed by value, either by physical copy or by giving an access path • Physical copy simply initializes the formal parameter using the corresponding actual parameter value • The formal parameter then acts as a local variable in the subprogram, thus implementing in-mode semantics. • Giving the callee (the called subprogram) the access path to the value of the actual parameter in the caller, • but that would require that the value be in a write-protected cell (one that can only be read).
Parameter-passing methods Implementation models of parameter passing • Pass-by-value (inmode) • Either by physical copy or by giving an access path • Disadvantages of the pass-by-value if physical copy is used • Requires additional storage duplicated space for the formal parameter, • either in the called subprogram or • in some area outside both the caller and the called subprogram. • Require to copy the actual parameter to the storage area for the corresponding formal parameter. • The storage and the copy operations can be costly
Parameter-passing methods Implementation models of parameter passing • Pass-by-value (inmode) • Either by physical copy or by giving an access path • Disadvantages of the pass-by-value parameters if transmitted by access path method • Must write-protect the parameter – difficult to enforce the write-protection • Indirect addressing Access of parameters is slow • Both disadvantages are costly for a large array • C++ provides a convenient and effective method for specifying write protection on pass-by-value parameters that are transmitted by access path.
Pass-by-Value /** This example illustrates calling a function by pass-by-value**/ #include <stdio.h> void func (int a, int b) /*Callee, a and b are formal parameters*/ { a += b; printf("In func, a = %d b = %d\n", a, b); } int main(void) { int x = 5, y = 7; func(x, y); /*caller, x and y are actual parameters*/ printf("In main, x = %d y = %d\n", x, y); return 0; } a = 5 b = 7 a = 12 x = 5 y = 7 The output of the program is: In func, a = 12 b = 7 In main, x = 5 y = 7
Parameter-passing methods Implementation models of parameter passing • Pass-by-result (for out mode parameters) • When a parameter is passed by result, no value is transmitted to the called subprogram (the callee). • The corresponding formal parameter acts as a local variable, its value is transmitted back to the caller’s actual parameter (i.e., a variable of a calling program unit) before control is transferred back to the caller (the calling program). • Actual parameter must be a variable • This change of a variable is an expected side-effect • Physical copy is usually used • Upon return, the formal parameter’s value is copied back to the caller
Parameter-passing methods Implementation models of parameter passing • Pass-by-result (for out mode parameters) • Disadvantage of physical copy • Requires extra storage and time for the copy operations if values are returned by copy. • Disadvantages of access path method • Difficult to implement pass-by-result by transmitting an access path for its Indirect addressing. • The problem is in ensuring that the initial value of the actual parameter is not used in the called subprogram. • Need to read-protect the actual parameter
Parameter-passing methods Implementation models of parameter passing • Problem with the pass-by-result model • There can be an actual parameter collision. Consider the following C# method: void Fixer (out intx, out inty) { x = 10; y = 20; } … f.Fixer (out a, out a); • The order in which the result parameter are copied determines their values. • If at the end of the execution of Fixer, the formal parameter x is assigned to its corresponding actual parameter first, then the value of the actual parameter a in the caller will be 20. If y is assigned first, then the value of the a in the called will be 10. {y=20; x=10} • Never can get 10, 20 as output. x = 10 y = 20 a = 10 20
Parameter-passing methods Implementation models of parameter passing • Problem with the pass-by-result model • The implementor may be able to choose between two different times to evaluate the addresses of the actual parameters: at the time of the call or at the time of the return. Consider the following C# method: voidDoit(out intx, int index) { x = 10; index = 20; } … sub = 15; f.Doit (list[sub], sub); • The implementor must choose the time to bind this parameter to an address - If the address is computed on entry to the method, the value 10 will be returned to list[15]; if computed just before return, 10 will return to list [20]. This makes programs unportable. index = 20 x = 10 f.Doit did not pass any value to the called program. List[15] … sub = 15 20 10 …
Parameter-passing methods Implementation models of parameter passing • Problem with the pass-by-result model • The implementor may be able to choose between two different times to evaluate the addresses of the actual parameters: at the time of the call or at the time of the return. Consider the following C# method: voidDoit(out intx, int index) { x = 10; index = 20; } … sub = 15; f.Doit (list[sub], sub); • The implementor must choose the time to bind this parameter to an address - If the address is computed on entry to the method, the value 10 will be returned to list[15]; if computed just before return, 10 will return to list [20]. This makes programs unportable. index = 20 x = 10 f.Doit did not pass any value to the called program. List[20] … sub = 15 20 10 …
Parameter-passing methods Implementation models of parameter passing • Pass-by-value-result (inout mode) • This is inout mode implemented with physical copy both ways for copying data values back and forth. • Initialize the formal parameter usingthe value of the actual parameter. Then it acts a local variable. • The formal parameters must have local storage associated with the called subprogram before control is transferred back to the caller (the calling program). • At subprogram termination, the value of the formal parameter is transmitted back to the actual parameter.