9 subprograms

2,284 views

Published on

Published in: Technology
0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,284
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
6
Embeds 0
No embeds

No notes for slide

9 subprograms

  1. 1. ICS 313 - Fundamentals of Programming Languages 19. Subprograms9.2 Fundamentals of SubprogramsGeneral characteristics of subprogramsA subprogram has a single entry pointThe caller is suspended during execution of the called subprogramControl always returns to the caller when the called subprogram’sexecution terminatesBasic definitionsA subprogram definition is a description of the actions of the subprogramabstractionA subprogram call is an explicit request that the subprogram be executedA subprogram header is the first line of the definition, including the name,the kind of subprogram, and the formal parametersThe parameter profile of a subprogram is the number, order, and types ofits parametersThe protocol of a subprogram is its parameter profile plus, if it is a function,its return typeA subprogram declaration provides the protocol, but not the body, of thesubprogram
  2. 2. ICS 313 - Fundamentals of Programming Languages 29.2 Fundamentals of Subprograms (continued)A formal parameter is a dummy variable listed in the subprogram header and used in thesubprogramAn actual parameter represents a value or address used in the subprogram call statementActual/Formal Parameter CorrespondencePositionalKeyworde.g. SORT(LIST => A, LENGTH => N);Advantage: order is irrelevantDisadvantage: user must know the formal parameter’s namesDefault Values:e.g.procedure SORT(LIST : LIST_TYPE; LENGTH : INTEGER := 100);...SORT(LIST => A);Procedures provide user-defined statementsFunctions provide user-defined operators9.3 Design Issues for SubprogramsWhat parameter passing methods are provided?Are parameter types checked?Are local variables static or dynamic?What is the referencing environment of a passed subprogram?Are parameter types in passed subprograms checked?Can subprogram definitions be nested?Can subprograms be overloaded?Are subprograms allowed to be generic?Is separate or independent compilation supported?
  3. 3. ICS 313 - Fundamentals of Programming Languages 39.4 Local referencing environmentsIf local variables are stack-dynamic:AdvantagesSupport for recursionStorage for locals is shared among some subprogramsDisadvantagesAllocation/deallocation timeIndirect addressingSubprograms cannot be history sensitiveStatic locals are the oppositeLanguage ExamplesFORTRAN 77 and 90 - most are static, but the implementor canchoose either(User can force static with SAVE)C - both (variables declared to be static are)(default is stack dynamic)Pascal, Java, and Ada - dynamic only9.5 Parameter Passing MethodsWe discuss these at several different levelsSemantic Models: in mode, out mode, inout modeConceptual Models of TransferPhysically move a valueMove an access path
  4. 4. ICS 313 - Fundamentals of Programming Languages 49.5 Parameter Passing Methods (continued)Implementation ModelsPass-by-value (in mode)Either by physical move or access pathDisadvantages of access path methodMust write-protect in the called subprogramAccesses cost more (indirect addressing)Disadvantages of physical moveRequires more storage (duplicated space)Cost of the moves (if the parameter is large)9.5 Parameter Passing Methods (continued)Pass-by-result (out mode)Local’s value is passed back to the callerPhysical move is usually usedDisadvantages:If value is passed, time and spaceIn both cases, order dependence may be a probleme.g.procedure sub1(y: int, z: int);...sub1(x, x);Value of x in the caller depends on order of assignments at the returnPass-by-value-result (inout mode)Physical move, both waysAlso called pass-by-copyDisadvantages:Those of pass-by-resultThose of pass-by-value
  5. 5. ICS 313 - Fundamentals of Programming Languages 59.5 Parameter Passing Methods (continued)Pass-by-reference (inout mode)Pass an access pathAlso called pass-by-sharingAdvantage: passing process is efficient (no copying and no duplicatedstorage)DisadvantagesSlower accessesAllows aliasingActual parameter collisionse.g. procedure sub1(a: int, b: int);...sub1(x, x);Array element collisionse.g.sub1(a[i], a[j]); /* if i = j */Also, sub2(a, a[i]); (a different one)Collision between formals and globals– Root cause of all of these is: The called subprogram is provided wider access tononlocals than is necessary– Pass-by-value-result does not allow these aliases (but has other problems!)9.5 Parameter Passing Methods (continued)Pass-by-name (multiple mode)By textual substitutionFormals are bound to an access method at the time of the call,but actual binding to a value or address takes place at the timeof a reference or assignmentPurpose: flexibility of late bindingResulting semantics:If actual is a scalar variable, it is pass-by-referenceIf actual is a constant expression, it is pass-by-valueIf actual is an array element, it is like nothing elsee.g.procedure sub1(x: int; y: int);beginx := 1;y := 2;x := 2;y := 3;end;sub1(i, a[i]);
  6. 6. ICS 313 - Fundamentals of Programming Languages 69.5 Parameter Passing Methods (continued)If actual is an expression with a reference to a variable that is alsoaccessible in the program, it is also like nothing elsee.g. (assume k is a global variable)procedure sub1(x: int; y: int; z: int);begink := 1;y := x;k := 5;z := x;end;sub1(k+1, j, i);Disadvantages of pass by nameVery inefficient referencesToo tricky; hard to read and understand9.5 Parameter Passing Methods (continued)Language ExamplesFORTRANBefore 77, pass-by-reference77 - scalar variables are often passed by value-resultALGOL 60Pass-by-name is default; pass-by-value is optionalALGOL WPass-by-value-resultCPass-by-valuePascal and Modula-2Default is pass-by-value; pass-by-reference is optionalC++Like C, but also allows reference type parameters, which provide the efficiency ofpass-by-reference with in-mode semantics
  7. 7. ICS 313 - Fundamentals of Programming Languages 79.5 Parameter Passing Methods (continued)AdaAll three semantic modes are availableIf out, it cannot be referencedIf in, it cannot be assignedJavaLike C++, except only referencesType checking parameters(Now considered very important for reliability)FORTRAN 77 and original C: nonePascal, FORTRAN 90, Java, and Ada: it is alwaysrequiredANSI C and C++: choice is made by the user9.5 Parameter Passing Methods (continued)Implementing Parameter PassingALGOL 60 and most of its descendants use the run-time stackValue - copy it to the stack; references are indirect to the stackResult - sameReference - regardless of form, put the address in the stackName - run-time resident code segments or subprograms evaluate theaddress of the parameter; called for each reference to the formal; these arecalled thunksVery expensive, compared to reference or value-result
  8. 8. ICS 313 - Fundamentals of Programming Languages 89.5 Parameter Passing Methods (continued)One possible stack implementation of the common parameter-passing methods9.5 Parameter Passing Methods (continued)AdaSimple variables are passed by copy (value-result)Structured types can be either by copy or referenceThis can be a problem, becausea) Of aliases (reference allows aliases, but value-result does not)b) Procedure termination by error can produce different actualparameter resultsPrograms with such errors are “erroneous”
  9. 9. ICS 313 - Fundamentals of Programming Languages 99.5 Parameter Passing Methods (continued)Multidimensional Arrays as ParametersIf a multidimensional array is passed to a subprogram and thesubprogram is separately compiled, the compiler needs to know thedeclared size of that array to build the storage mapping functionC and C++Programmer is required to include the declared sizes of all but the first subscript inthe actual parameterThis disallows writing flexible subprogramsSolution: pass a pointer to the array and the sizes of the dimensions as otherparameters; the user must include the storage mapping function, which is in termsof the size parameters (See example, p. 371)PascalNot a problem (declared size is part of the array’s type)AdaConstrained arrays - like PascalUnconstrained arrays - declared size is part of the object declaration(See example p. 371)(Java is similar)9.5 Parameter Passing Methods (continued)Pre-90 FORTRANFormal parameter declarations for arrays can include passed parameterse.g.SUBPROGRAM SUB(MATRIX, ROWS, COLS, RESULT)INTEGER ROWS, COLSREAL MATRIX (ROWS, COLS), RESULT...ENDDesign Considerations for Parameter Passing1. Efficiency2. One-way or two-wayThese two are in conflict with one another!Good programming => limited access to variables, which means one-waywhenever possibleEfficiency => pass by reference is fastest way to pass structures ofsignificant sizeAlso, functions should not allow reference parameters
  10. 10. ICS 313 - Fundamentals of Programming Languages 109.6 Parameters that are Subprogram NamesIssuesAre parameter types checked?Early Pascal and FORTRAN 77 do notLater versions of Pascal and FORTRAN 90 doAda does not allow subprogram parametersJava does not allow method names to be passed as parametersC and C++ - pass pointers to functions; parameters can be type checkedWhat is the correct referencing environment for asubprogram that was sent as a parameter?Possibilities:a. It is that of the subprogram that enacted it - Shallow bindingb. It is that of the subprogram that declared it - Deep bindingc. It is that of the subprogram that passed it - Ad hoc binding(Has never been used)9.6 Parameters that are Subprogram NamesFor static-scoped languages, deep binding is most naturalFor dynamic-scoped languages, shallow binding is most naturalExample:sub1sub2sub3call sub4(sub2)sub4(subx)call subxcall sub3What is the referencing environment of sub2 when it is called in sub4?Shallow binding => sub2, sub4, sub3, sub1Deep binding => sub2, sub1
  11. 11. ICS 313 - Fundamentals of Programming Languages 119.7 Overloaded SubprogramsDef: An overloaded subprogram is one that has thesame name as another subprogram in thesame referencing environmentC++ and Ada have overloaded subprograms built-in,and users can write their own overloadedsubprograms9.8 Generic SubprogramsA generic or polymorphic subprogram is one that takesparameters of different types on different activationsOverloaded subprograms provide ad hoc polymorphismA subprogram that takes a generic parameter that isused in a type expression that describes the type of theparameters of the subprogram provides parametricpolymorphismExamples of parametric polymorphismAdaTypes, subscript ranges, constant values, etc., can be genericin Ada subprograms and packages e.g. - see next page
  12. 12. ICS 313 - Fundamentals of Programming Languages 129.8 Generic Subprograms (continued)generictype ELEMENT is private;type VECTOR is array (INTEGER range <>) of ELEMENT;procedure GENERIC_SORT(LIST: in out VECTOR);procedure GENERIC_SORT(LIST: in out VECTOR)isTEMP : ELEMENT;beginfor INDEX_1 in LISTFIRST .. INDEX_1PRED(LISTLAST) loopfor INDEX_2 in INDEXSUCC(INDEX_1) .. LISTLAST loopif LIST(INDEX_1) > LIST(INDEX_2) thenTEMP := LIST (INDEX_1);LIST(INDEX_1) := LIST(INDEX_2);LIST(INDEX_2) := TEMP;end if;end loop; -- for INDEX_1 ...end loop; -- for INDEX_2 ...end GENERIC_SORT;procedure INTEGER_SORT is new GENERIC_SORT(ELEMENT => INTEGER; VECTOR => INT_ARRAY);9.8 Generic Subprograms (continued)Ada generics are used to provide the functionality of parameters that aresubprograms; generic part is a subprogramExample:genericwith function FUN(X : FLOAT) return FLOAT;procedure INTEGRATE(LOWERBD : in FLOAT;UPPERBD : in FLOAT;RESULT : out FLOAT);procedure INTEGRATE(LOWERBD : in FLOAT;UPPERBD : in FLOAT;RESULT : out FLOAT) isFUNVAL : FLOAT;begin...FUNVAL := FUN(LOWERBD);...end;INTEGRATE_FUN1 is new INTEGRATE(FUN => FUN1);
  13. 13. ICS 313 - Fundamentals of Programming Languages 139.8 Generic Subprograms (continued)C++Templated functionse.g.template <class Type>Type max(Type first, Type second) {return first > second ? first : second;}C++ template functions are instantiated implicitly when the functionis named in a call or when its address is taken with the & operator9.8 Generic Subprograms (continued)Another example:template <class Type>void generic_sort(Type list[], int len) {int top, bottom;Type temp;for (top = 0; top < len - 2; top++)for (bottom = top + 1; bottom < len - 1; bottom++) {if (list[top] > list[bottom]) {temp = list [top];list[top] = list[bottom];list[bottom] = temp;} //** end of for (bottom = ...} //** end of generic_sortExample use:float flt_list[100];...generic_sort(flt_list, 100); // Implicit// instantiation
  14. 14. ICS 313 - Fundamentals of Programming Languages 149.9 Separate & Independent CompilationIndependent compilation is compilation of some of the units ofa program separately from the rest of the program, without thebenefit of interface informationSeparate compilation is compilation of some of the units of aprogram separately from the rest of the program, usinginterface nformation to check the correctness of the interfacebetween the two partsLanguage Examples:FORTRAN II to FORTRAN 77 - independentFORTRAN 90, Ada, C++, Java - separatePascal - allows neither9.10 Design Issues for FunctionsAre side effects allowed?Two-way parameters (Ada does not allow)Nonlocal reference (all allow)What types of return values are allowed?Language Examples (for possible return types):FORTRAN, Pascal - only simple typesC - any type except functions and arraysAda - any type (but subprograms are not types)C++ and Java - like C, but also allow classes to be returned
  15. 15. ICS 313 - Fundamentals of Programming Languages 159.11 Accessing Nonlocal EnvironmentsThe nonlocal variables of a subprogramare those that are visible but not declaredin the subprogramGlobal variables are those that may bevisible in all of the subprograms of aprogramMethods:1. FORTRAN COMMONThe only way in pre-90 FORTRANs to access nonlocalvariablesCan be used to share data or share storage9.11 Accessing Nonlocal Environments (continued)2. Static scoping - discussed in Chapter 53. External declarations - CSubprograms are not nestedGlobals are created by external declarations(they are simply defined outside any function)Access is by either implicit or explicit declarationDeclarations (not definitions) give types to externally defined variables(and say they are defined elsewhere)4. External modules - AdaMore about these later (Chapter 11)5. Dynamic Scope - discussed in Chapter 5
  16. 16. ICS 313 - Fundamentals of Programming Languages 169.12 User-Defined Overloaded OperatorsNearly all programming languages have overloaded operatorsUsers can further overload operators in C++ and Ada (Not carried over intoJava)Example (Ada) (assume VECTOR_TYPE has been defined to be an array typewith INTEGER elements):function "*"(A, B : in VECTOR_TYPE)return INTEGER isSUM : INTEGER := 0;beginfor INDEX in Arange loopSUM := SUM + A(INDEX) * B(INDEX);end loop;return SUM;end "*";Are user-defined overloaded operators good or bad?9.13 CoroutinesA coroutine is a subprogram that has multiple entries and controlsthem itselfAlso called symmetric controlA coroutine call is named a resumeThe first resume of a coroutine is to its beginning, but subsequentcalls enter at the point just after the last executed statement in thecoroutineTypically, coroutines repeatedly resume each other, possibly foreverCoroutines provide quasi-concurrent execution of program units(the coroutines)Their execution is interleaved, but not overlapped
  17. 17. ICS 313 - Fundamentals of Programming Languages 179.13 Coroutines (continued)Examples

×