Presentation is loading. Please wait.

Presentation is loading. Please wait.

第九章 副程式 (Subprograms). 淡江大學資訊管理系侯永昌 1 Introduction §Two fundamental abstraction facilities l Process abstraction (this chapter) : by subprogram, increase.

Similar presentations


Presentation on theme: "第九章 副程式 (Subprograms). 淡江大學資訊管理系侯永昌 1 Introduction §Two fundamental abstraction facilities l Process abstraction (this chapter) : by subprogram, increase."— Presentation transcript:

1 第九章 副程式 (Subprograms)

2 淡江大學資訊管理系侯永昌 1 Introduction §Two fundamental abstraction facilities l Process abstraction (this chapter) : by subprogram, increase readability by hiding the small-scale details l Data abstraction (Chapter 11) : by user- defined abstract data type Encapsulation Information hiding

3 淡江大學資訊管理系侯永昌 2 Fundamentals of Subprograms §General characteristics of subprograms: 1. A subprogram has a single entry point 2. The caller is suspended during execution of the called subprogram ,一次只能執 行一個 program 3. Control always returns to the caller when the called subprograms execution terminates

4 淡江大學資訊管理系侯永昌 3 Fundamentals of Subprograms §A subprogram definition is a description of the actions of the subprogram abstraction §A subprogram call is an explicit request that the subprogram be executed §A subprogram header is the first line of the definition, including the name, the kind of subprogram, and the formal parameters §The parameter profile of a subprogram is the number, order, and types of its parameters

5 淡江大學資訊管理系侯永昌 4 Fundamentals of Subprograms §The protocol of a subprogram is its parameter profile plus, if it is a function, its return type §A subprogram declaration provides the protocol, but not the body, of the subprogram §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

6 淡江大學資訊管理系侯永昌 5 Actual/Formal Parameter Correspondence 1. Positional 2. Keyword: SORT(LIST => A, LENGTH => N); l Advantage: order is irrelevant l Disadvantage: user must know the formal parameters names §Ada 甚至允許 formal parameter 使用 Default Values: e.g. procedure SORT(LIST : LIST_TYPE; LENGTH : INTEGER := 100);... SORT(LIST => A); length 的 default 值是 100

7 淡江大學資訊管理系侯永昌 6 Fundamentals of Subprograms §Procedures provide user-defined statements §Functions provide user-defined operators

8 淡江大學資訊管理系侯永昌 7 Design Issues for Subprograms 1. What parameter passing methods are provided? 2. Are parameter types checked? 3. Are local variables static or dynamic? 4. Can subprogram definitions appear in other subprogram definitions? 5. What is the referencing environment of a passed subprogram? 6. Can subprograms be overloaded? 7. Are subprograms allowed to be generic?

9 淡江大學資訊管理系侯永昌 8 Local referencing environments §If local variables are stack-dynamic: l Advantages: a. Support for recursion b. Storage for locals is shared among some subprograms l Disadvantages: a. Allocation/deallocation time b. Indirect addressing c. Subprograms cannot be history sensitive §Static locals are the opposite

10 淡江大學資訊管理系侯永昌 9 Local referencing environments §Language Examples: 1. FORTRAN 77 and 90 - most are static, but the implementor can choose either (User can force static with SAVE statement) 2. C - both (variables declared to be static are) (default is stack-dynamic) 3. Pascal, Java, and Ada - stack-dynamic only

11 淡江大學資訊管理系侯永昌 10 Parameter Passing Methods §We discuss these at several different levels: l Semantic models: in mode out mode inout mode l Conceptual models of transfer: Physically move a value Move an access path

12 淡江大學資訊管理系侯永昌 11 Models of Parameter Passing

13 淡江大學資訊管理系侯永昌 12 Parameter Passing Methods 1. Pass-by-value (in mode) :將 actual parameter 的值傳送到 formal parameter 內, 成為它的 initial value l Either by physical move or access path l Disadvantages of access path method: Must write-protect in the called subprogram Accesses cost more (indirect addressing) l Disadvantages of physical move: Requires more storage (duplicated space) Cost of the moves (if the parameter is large)

14 淡江大學資訊管理系侯永昌 13 Parameter Passing Methods 2. Pass-by-result (out mode) :在 subprogram 結 束的那一瞬間,將 formal parameter 的值傳送 回 actual parameter 中 l Physical move is usually used l Disadvantages: If value is passed, time and space are required In both cases, order dependence may be a problem e.g. procedure sub1(y: int, z: int);... sub1(x, x); Value of x in the caller depends on order of assignments at the return

15 淡江大學資訊管理系侯永昌 14 Parameter Passing Methods 3. Pass-by-value-result (inout mode) l Pass-by-value + pass-by-result l Physical move, both ways l Also called pass-by-copy l Disadvantages: Those of pass-by-result Those of pass-by-value

16 淡江大學資訊管理系侯永昌 15 Parameter Passing Methods 4. Pass-by-reference (inout mode) :將 actual parameter 的 access path (e.g., pointer, address,...) 傳送到 formal parameter 中,因此 actual parameter 是 caller 與 callee 的 shared variable l Pass an access path l Also called pass-by-sharing l Advantage: passing process is efficient (no copying and no duplicated storage)

17 淡江大學資訊管理系侯永昌 16 Parameter Passing Methods §Pass-by-reference - Disadvantages: a. Slower accesses : indirect addressing Actual parameter: p1 Formal parameter: A b. Allows aliasing :影響 readability, reliability 和造成 verification 的困難 i. Actual parameter collisions: e.g. procedure sub1(a: int, b: int);... sub1(x, x);

18 淡江大學資訊管理系侯永昌 17 Parameter Passing Methods §Pass-by-reference - disadvantages (cont) ii. Array element collisions: e.g. sub1(a[i], a[j]); /* if i = j */ Also, sub2(a, a[i]); (a different one) iii. Collision between formals and globals l Root cause of all of these is: The called subprogram is provided wider access to nonlocals than is necessary l Pass-by-value-result does not allow these aliases (but has other problems!)

19 淡江大學資訊管理系侯永昌 18 Parameter Passing Methods §Pass-by-reference - disadvantages (cont) § 例: int * global; void main ( ) { extern int * global;... sub (global);...} void sub (int * param) { extern int * global;... } global 與 param 為 aliasing

20 淡江大學資訊管理系侯永昌 19 Parameter Passing Methods 5. Pass-by-name (multiple mode) l By textual substitution l Formal variables are bound to an access method at the time of the call, but actual binding to a value or address takes place at the time of a reference or assignment l Purpose: flexibility of late binding

21 淡江大學資訊管理系侯永昌 20 Pass-by-name §Resulting semantics: l If actual is a scalar variable, it is pass-by-reference l If actual is a constant expression, it is pass-by-value l If actual is an array element, it is like nothing else e.g. procedure sub1(x: int; y: int); begin x := 1; y := 2; x := 2; y := 3; end; sub1(i, a[i]); a[1] = 2 a[2] = 3

22 淡江大學資訊管理系侯永昌 21 Pass-by-name l If actual is an expression with a reference to a variable that is also accessible in the program, it is also like nothing else e.g. (assume k is a global variable) procedure sub1(x: int; y: int; z: int); begin k := 1; y := x; k := 5; z := x; end; sub1(k+1, j, i); j = 2 i = 6

23 淡江大學資訊管理系侯永昌 22 Pass-by-name §procedure sum (adder, index, length); real adder; integer index, length; begin real tempsum; tempsum := 0.0; for index := 1 step 1 until length do tempsum := tempsum + adder; sum := tempsum; end;  sum(A, I, 100);  100*A  sum(A[I], I, 100);   A[I]  sum(A[I]*A[I], I, 100);   A[I] 2  sum(A[I]*B[I], I, 100);   A[I]*B[I}

24 淡江大學資訊管理系侯永昌 23 Parameter Passing Methods §Disadvantages of pass by name: l Very inefficient references l Too tricky; hard to read and understand

25 淡江大學資訊管理系侯永昌 24 Parameter Passing Methods 1. FORTRAN l Before 77, pass-by-reference l 77 - scalar variables are often passed by value- result 2. ALGOL 60 l Pass-by-name is default; pass-by-value is optional 3. ALGOL W: Pass-by-value-result 4. C: Pass-by-value

26 淡江大學資訊管理系侯永昌 25 Parameter Passing Methods 5. Pascal and Modula-2 l Default is pass-by-value; pass-by-reference is optional 6. C++ l Like C, but also allows reference type parameters, which provide the efficiency of pass-by-reference with in-mode semantics 7. Ada: All three semantic modes are available l If out, it cannot be referenced l If in, it cannot be assigned 8. Java: Like C++, except only references

27 淡江大學資訊管理系侯永昌 26 Parameter Passing Methods §Type checking parameters (now considered very important for reliability ,保證 software 的 reliability) l FORTRAN 77 and original C: none l Pascal, FORTRAN 90, Java, and Ada: it is always required l ANSI C and C++: choice is made by the user

28 淡江大學資訊管理系侯永昌 27 Implementing Parameter Passing §ALGOL 60 and most of its descendants use the run-time stack §Pass by value - copy it to the stack; references are indirect to the stack §Pass by result - same §Pass by reference - regardless of form, put the address in the stack §Pass by name - run-time resident code segments or subprograms evaluate the address of the parameter; called for each reference to the formal; these are called thunks l Very expensive, compared to reference or value-result

29 淡江大學資訊管理系侯永昌 28 Stack Implementation of Parameter-Passing

30 淡江大學資訊管理系侯永昌 29 Implementing Parameter Passing §Ada l Simple variables are passed by copy (value-result) l Structured types can be either by copy or reference l This can be a problem, because of a) Aliases (reference allows aliases, but value- result does not) b) Procedure termination by error can produce different actual parameter results

31 淡江大學資訊管理系侯永昌 30 Multidimensional Arrays as Parameters §If a multidimensional array is passed to a subprogram and the subprogram is separately compiled, the compiler needs to know the declared size of that array to build the storage mapping function § 對於 row (column)-major 的 language 而言, 至少必須要知道 array 的 column (row) 大小 Address[i, j] = address[0,0] + i*number_of_column + j

32 淡江大學資訊管理系侯永昌 31 Multidimensional Arrays as Parameters §C and C++ l Programmer is required to include the declared sizes of all but the first subscript in the actual parameter l This disallows writing flexible subprograms l Solution: pass a pointer to the array and the sizes of the dimensions as other parameters; the user must include the storage mapping function, which is in terms of the size parameters

33 淡江大學資訊管理系侯永昌 32 Multidimensional Arrays as Parameters §Pascal l Not a problem (declared size is part of the array type) §Ada l Constrained arrays - like Pascal l Unconstrained arrays - declared size is part of the object declaration (Java is similar)

34 淡江大學資訊管理系侯永昌 33 Multidimensional Arrays as Parameters §Pre-90 FORTRAN l Formal parameter declarations for arrays can include passed parameters, e.g. SUBPROGRAM SUB(MATRIX, ROWS, COLS, RESULT) INTEGER ROWS, COLS REAL MATRIX (ROWS, COLS), RESULT... END

35 淡江大學資訊管理系侯永昌 34 Design Considerations for Parameter Passing §1. One-way or two-way: information hiding l These two are in conflict with one another! l Good programming => limited access to variables, which means one-way whenever possible l Efficiency => pass by reference is fastest way to pass structures of significant size l Also, functions should not allow reference parameters ,希望避免 side-effect

36 淡江大學資訊管理系侯永昌 35 Design Considerations for Parameter Passing §2. Efficiency: 對與一個大型的 array ,雖然實際上只需要 one-way transmission ,但是 pass-by-value 需 要做 array 的 copy ,浪費很多的時間和空間。 因此基於 efficiency 的考慮, array 常常用 pass- by-reference 的方式來 implement

37 淡江大學資訊管理系侯永昌 36 Parameters that are Subprogram Names §Issues: 1. Are parameter types checked? 通常被當成 parameter 的 function 必須連帶它的 formal parameter 及 data type ,以方便做 static check l Early Pascal and FORTRAN 77 do not l Later versions of Pascal and FORTRAN 90 do l Ada does not allow subprogram parameters l Java does not allow method names to be passed as parameters l C and C++ pass pointers to functions; parameters can be type checked

38 淡江大學資訊管理系侯永昌 37 Parameters that are Subprogram Names § 例: procedure integrate (function fun (x : real) : real; lowerbd, upperbd : real; var result : real);... var funval : real; begin... funval = fun (lowerbd);... end;

39 淡江大學資訊管理系侯永昌 38 Parameters that are Subprogram Names 2. What is the correct referencing environment for a subprogram that was sent as a parameter? a. It is that of the subprogram that enacted it: Shallow binding, dynamic scoping b. It is that of the subprogram that declared it: Deep binding, static scoping c. It is that of the subprogram that passed it: Ad hoc binding (Has never been used)

40 淡江大學資訊管理系侯永昌 39 Parameters that are Subprogram Names §For static-scoped languages, deep binding is most natural §For dynamic-scoped languages, shallow binding is most natural

41 淡江大學資訊管理系侯永昌 40 Example: sub1 sub2 sub3 call sub4(sub2) sub4(subx) call subx call sub3  What is the referencing environment of sub2 when it is called in sub4 ? Shallow binding => sub2, sub4, sub3, sub1 Deep binding => sub2, sub1 Ad hoc binding => sub2, sub3 Parameters that are Subprogram Names

42 淡江大學資訊管理系侯永昌 41 Overloaded Subprograms §Overloaded operator : has multiple meaning distinguished by the types of its operands §An overloaded subprogram is one that has the same name as another subprogram in the same referencing environment, distinguished by the types of its parameters and/or the type of the return value §C++ and Ada have overloaded subprograms built-in, and users can write their own overloaded subprograms

43 淡江大學資訊管理系侯永昌 42 Generic Subprograms §A generic or polymorphic subprogram is one that takes parameters of different types on different activations §Overloaded subprograms provide ad hoc polymorphism §A subprogram that takes a generic parameter that is used in a type expression that describes the type of the parameters of the subprogram provides parametric polymorphism

44 淡江大學資訊管理系侯永昌 43 Generic Subprograms 1. Ada l Types, subscript ranges, constant values, etc., can be generic in Ada subprograms and packages, e.g. generic type ELEMENT is private; type VECTOR is array (INTEGER range <>) of ELEMENT; procedure GENERIC_SORT(LIST: in out VECTOR);

45 淡江大學資訊管理系侯永昌 44 Generic Subprograms procedure GENERIC_SORT(LIST: in out VECTOR)is TEMP : ELEMENT; begin for INDEX_1 in LIST'FIRST.. INDEX_1'PRED(LIST'LAST) loop for INDEX_2 in INDEX'SUCC(INDEX_1).. LIST'LAST loop if LIST(INDEX_1) > LIST(INDEX_2) then TEMP := 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;

46 淡江大學資訊管理系侯永昌 45 Generic Subprograms procedure INTEGER_SORT is new GENERIC_SORT( ELEMENT => INTEGER; VECTOR => INT_ARRAY);

47 淡江大學資訊管理系侯永昌 46 Generic Subprograms §Ada generics are used to provide the functionality of parameters that are subprograms; generic part is a subprogram §Example: generic with function FUN(X : FLOAT) return FLOAT; procedure INTEGRATE(LOWERBD : in FLOAT; UPPERBD : in FLOAT; RESULT : out FLOAT);

48 淡江大學資訊管理系侯永昌 47 Generic Subprograms procedure INTEGRATE(LOWERBD : in FLOAT; UPPERBD : in FLOAT; RESULT : out FLOAT) is FUNVAL : FLOAT; begin... FUNVAL := FUN(LOWERBD);... end; INTEGRATE_FUN1 is new INTEGRATE(FUN => FUN1);

49 淡江大學資訊管理系侯永昌 48 Generic Subprograms 2. C++ l Templated functions e.g. template Type max(Type first, Type second) { return first > second ? first : second; }

50 淡江大學資訊管理系侯永昌 49 Generic Subprograms §C++ template functions are instantiated implicitly when the function is named in a call or when its address is taken with the & operator §Another example: template void generic_sort(Type list[], int, len) { int top, bottom; Type temp;

51 淡江大學資訊管理系侯永昌 50 Generic Subprograms 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_sort

52 淡江大學資訊管理系侯永昌 51 Generic Subprograms §Example use: float flt_list[100];... generic_sort(flt_list, 100); // Implicit instantiation

53 淡江大學資訊管理系侯永昌 52 Separate & Independent Compilation §Independent compilation is compilation of some of the units of a program separately from the rest of the program, without the benefit of interface information §Separate compilation is compilation of some of the units of a program separately from the rest of the program, using interface information to check the correctness of the interface between the two parts.

54 淡江大學資訊管理系侯永昌 53 Separate & Independent Compilation §Separate compilation 對於建立大型的 software 很重要,需要修改其中的某一個 module 時, 只需要重新 compile 那一個 module 即可,而不 需要將整個系統重新 compile § 最後利用 linker 將所有 separate compile 的 module link 起來就可以了 § 為了要達成 separate compile 的目的,每一個 subprogram 的 parameter 的數目、形態、以及 return value( 如果是 function) ,必須能為別的 subprogram 所知道

55 淡江大學資訊管理系侯永昌 54 Separate & Independent Compilation §Language Examples: l FORTRAN II to FORTRAN 77 - independent l FORTRAN 90, Ada, C++, Java - separate l Pascal - allows neither

56 淡江大學資訊管理系侯永昌 55 Design Issues for Functions 1. Are side effects allowed? parameter to function should be in-mode only ,這樣 子可以防止 aliasing 和 global variable 的問題 a. Two-way parameters (Ada does not allow) b. Nonlocal reference (all allow) 2. What types of return values are allowed? 大部分的 language 只允許 return simple type 的 value 1. FORTRAN, Pascal - only simple types 2. C - any type except functions and arrays 3. Ada - any type (but subprograms are not types) 4. C++ and Java - like C, but also allow classes to be returned

57 淡江大學資訊管理系侯永昌 56 Accessing Nonlocal Environments §The nonlocal variables of a subprogram are those that are visible but not declared in the subprogram §Global variables are those that may be visible in all of the subprograms of a program

58 淡江大學資訊管理系侯永昌 57 Accessing Nonlocal Environments §Methods: 1. FORTRAN COMMON blocks l The only way in pre-90 FORTRANs to access nonlocal variables l Can be used to share data or share storage 2. Static scoping - discussed in Chapter 5 3. External modules - Ada l More about these later (Chapter 11) 4. Dynamic Scope - discussed in Chapter 5

59 淡江大學資訊管理系侯永昌 58 Accessing Nonlocal Environments §Methods (continued): 5. External declarations - C l Subprograms are not nested l Globals are created by external declarations (they are simply defined outside any function) l Access is by either implicit or explicit declaration l Declarations (not definitions) give types to externally defined variables (and say they are defined elsewhere)

60 淡江大學資訊管理系侯永昌 59 User-Defined Overloaded Operators §Nearly all programming languages have overloaded operators §Users can further overload operators in C++ and Ada (Not carried over into Java)

61 淡江大學資訊管理系侯永昌 60 User-Defined Overloaded Operators  Example (Ada) (assume VECTOR_TYPE has been defined to be an array type with INTEGER elements): function "*"(A, B : in VECTOR_TYPE) return INTEGER is SUM : INTEGER := 0; begin for INDEX in A'range loop SUM := SUM + A(INDEX) * B(INDEX); end loop; return SUM; end "*"; §Are user-defined overloaded operators good or bad?

62 淡江大學資訊管理系侯永昌 61 Coroutines §Coroutine are subprograms that have multiple entries and are controlled by themselves §Also called symmetric control §A coroutine call is named a resume §The first resume of a coroutine is to its beginning, but subsequent calls enter at the point just after the last executed statement in the coroutine

63 淡江大學資訊管理系侯永昌 62 Coroutines §Typically, coroutines repeatedly resume each other, possibly forever §Coroutines provide quasi-concurrent execution of program units (the coroutines) §Their execution is interleaved, but not overlapped

64 淡江大學資訊管理系侯永昌 63 Coroutines

65 淡江大學資訊管理系侯永昌 64 Coroutines

66 淡江大學資訊管理系侯永昌 65 Coroutines


Download ppt "第九章 副程式 (Subprograms). 淡江大學資訊管理系侯永昌 1 Introduction §Two fundamental abstraction facilities l Process abstraction (this chapter) : by subprogram, increase."

Similar presentations


Ads by Google