70 likes | 375 Views
Control Abstraction. Control abstraction takes many forms:. subprograms. procedures. functions. methods. operations. Primary distinction: void or non-void. ________________ = the data required to support run-time execution of the subprogram.
E N D
Control Abstraction Control abstraction takes many forms: subprograms procedures functions methods operations Primary distinction: void or non-void ________________ = the data required to support run-time execution of the subprogram Static language implementations store activation data together with the subprogram’s code. What’s wrong with this approach?
Parameter Passage by value The value of the argument is copied to the formal parameter at procedure entry. The formal parameter behaves like a local variable thereafter. by result The formal parameter behaves like a local variable (initially unassigned). The final value of the formal parameter is assigned to the argument at procedure exit. by value-result Like by value at procedure entry and by result at procedure exit by reference The formal parameter serves as an alias for its corresponding argument. (i.e., access to a formal parameter actually accesses the argument.) by name (see Algol 68) The procedure behaves as though every use of a formal parameter is textually replaced by its corresponding argument. Notes • arguments must map to memory location, excepting for by value. • arguments bound at procedure entry, except for by name.
An Example • Shared Variables • int k; • int[] arr; • Subprogram • public void alter(int a, int b) { • a = 2; • System.out.println(a, b, k, arr[1], arr[2]); • b = 3; • } • Driver • arr = new int[3]; • arr[1] = 1; • arr[2] = 2; • k = 1; • alter(k, arr[k]); • System.out.println(k, arr[1], arr[2]);
How are parameters implemented? by value The formal parameter requires storage of the specified type. This is assigned the value of the argument (expression evaluated) at call time. by result The formal parameter requires storage of the specified type. The parameter’s final value is assigned to the argument at return time. by value-result Both assignments (from by value and by result) are performed by reference The formal parameter stores the address of the argument (determined at call time). All accesses to the formal parameter require dereferencing. by name (see Algol 68) The compiler creates a code segment (a thunk) that determines the argument’s value/address at run time. Each formal parameter access invokes the proper thunk.
Another Example • Shared Variable • int arg; • Subprogram • public void foo(int p1, int p2) { • System.out.println(p1, p2, arg); • p1 = 1; • System.out.println(p1, p2, arg); • p2 = 2; • System.out.println(p1, p2, arg); • } • Driver • arg = 3 • foo(arg, arg); • System.out.println(arg);