1 / 128

Chapter 9 Subprograms

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

zelda
Download Presentation

Chapter 9 Subprograms

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 9Subprograms CS 350 Programming Language Design Indiana University – Purdue University Fort Wayne

  2. 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

  3. 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.

  4. 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

  5. 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

  6. ADT Java Example

  7. 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

  8. Fundamentals of subprogramsA subprogram call Caller (the calling program) Callee (the called subprogram)

  9. 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.

  10. Fundamentals of subprograms- Basic definitions • A subprogram definition • describes the interfaceand the actions of the subprogram abstraction • In Python, function definitions are executable; in all other languages, they are non-executable • In Ruby, function definitions can appear either in or outside of class definitions. If outside, they are methods of Object. They can be called without an object, like a function • In Lua, all functions are anonymous

  11. Fundamentals of subprograms- Basic definitions • A subprogramheaderis 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: void adder (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.

  12. 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

  13. Fundamentals of subprograms- Basic definitions • Function declarations in C and C++ are often called prototypes • A subprogram declarationprovides 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)

  14. Fundamentals of subprograms- Basic definitions • A formal parameteris 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 parameterrepresents a value or address used in the subprogram call statement

  15. Fundamentals of subprograms- Basic definitions • 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.

  16. 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

  17. Fundamentals of subprogramsActual/Formal Parameter Correspondence • Correspondence between actual & formal parameters – the binding of actual parameters to formal parameters by • 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 );

  18. Fundamentals of subprogramsActual/Formal Parameter Correspondence • 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 );

  19. Fundamentals of subprogramsActual/Formal Parameter Correspondence • 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

  20. Fundamentals of subprogramsActual/Formal Parameter Correspondence • 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 KwC functionComputePay( Income : Float; Exemptions : Integer := 1; -- a default value TaxRate : Float ) returnFloat; ------------------------------------------------- Pay := ComputePay( 20000.0, TaxRate => 0.15 );

  21. Fundamentals of subprogramsActual/Formal Parameter Correspondence • C# allows certain methods to have a variable number of parameters • But, the parameters must be of the same type PC 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); } }

  22. Fundamentals of subprogramsActual/Formal Parameter Correspondence • 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); } }

  23. Fundamentals of subprograms Procedures and Functions • There are two categories of subprograms • Proceduresare collection of statements that defined parameterized computations • They do not return values • Functions structurally resemble procedures but are semantically 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 • They are expected to produce no side effects • In practice, program functions have side effects

  24. 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

  25. 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

  26. 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?

  27. 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

  28. 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:

  29. Local referencing environments • Local variables can be stack-dynamic - Advantages • Support for recursion • Storage for locals is shared among some subprograms • Disadvantages • Allocation/de-allocation, initialization time • Indirect addressing • Subprograms cannot be history sensitive • Local variables can be static • Advantages and disadvantages are the opposite of those for stack-dynamic local variables

  30. 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 must 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, initialization time. • Accesses to stack-dynamic local variables must be indirect. Indirect addressing is slow • Subprograms cannot be history sensitive.

  31. Local referencing environments • Local variables can be static • Advantages and disadvantages are the opposite of those for stack-dynamic local variables • They requires no run-time overhead for allocation and deallocation. They are slightly more efficient. • If accessed directly, • They allow subprograms to 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.

  32. 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:

  33. Local referencing environments • In most contemporary languages, locals are stack dynamic • In C-based languages, locals are by default stack dynamic, but can be declared static • 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. • In Lua, all implicitly declared variables are global; local variables are declared with local and are stack dynamic

  34. Local referencing environments • 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.

  35. 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.

  36. Semantics Models of Parameter-Passing • In mode • Out mode • Inout mode

  37. Parameter-passing methodsThree semantics models of parameter passing when physical moves are used

  38. Parameter-passing methods • Parameter-passing methods are the ways in which parameters are transmitted to and/or from called subprogram. Let recognize • Caller calls Callee Calling program unit Called subprogram … Sub(a, b, c) void Sub(int x, int y, int z) {…} … Actual parameters Formal parameters

  39. 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)

  40. 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

  41. Parameter-passing methodsConceptualModels of Transfer • 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 - Move an access path to a value • an access path is transmitted • Most commonly, the access path is a simple pointer or reference. Think in terms of passing string’s object or array object.

  42. Parameter-passing methodsConceptualModels of Transfer • There are two conceptual models of passing parameters – of how data transfers take place in parameter transmission: • Physically move a value • Physically copy the values • Move an access path to a value • Using pointers/references

  43. Parameter-passing methodsThree semantics models of parameter passing when physical moves are used

  44. 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

  45. 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

  46. 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).

  47. 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

  48. 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.

  49. 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

More Related