8

Click here to load reader

parameter-passing modes - sce2.umkc.edusce2.umkc.edu/csee/leeyu/class/CS441/PA/Practice-Test2-Sol.pdf · For the meaning of the ... write a code sample that generates a dangling

Embed Size (px)

Citation preview

Page 1: parameter-passing modes - sce2.umkc.edusce2.umkc.edu/csee/leeyu/class/CS441/PA/Practice-Test2-Sol.pdf · For the meaning of the ... write a code sample that generates a dangling

CS441 Practice Test – 2 Nov. 8, 2004

1. Answer the following questions concerning programming languages: a. What are the purposes of the stack pointer (sp) and the frame pointer (fp)?

Why does a subroutine often need both? Why do compilers typically allocate space for arguments in the stack, even when they pass them in registers?

The Stack Pointer points to the top of stack, and changes continuously during the execution of a program. The stack is used by subroutines to store dynamic local data (that need to be valid only during the execution of the subroutine). It is thus typically used to store variables that are local to the subroutine, the incoming parameters, and the contents of (some of the) registers when other subroutines are called (so that they can use the registers). The size of the stack is increased on each subroutine call be decrementing the Stack Pointer -- recall that the stack grows downwards. Later, on subroutine return, the size of the stack is decremented by incrementing the stack pointer appropriately. The Frame Pointer is always equal to the value the stack pointer had when the current subroutine was called, before it was decremented for the current subroutine. Because the stack pointer is constantly changing, the data stored on the stack for the current subroutine are typically dereferenced via the Frame Pointer, since the Frame Pointer stays constant during the execution of the subroutine. We have limited registers and the local variables values should be preserved on calling another function and returning from it.

b. Describe four common parameter-passing modes. How does a programmer choose which one to use when?

They are 1. Value 2. Reference 3. Const-reference and 4. Call by Result (supported by ADA) When ever a parameter’s change in the subroutine to be reflected in the calling function then pass by reference should be used. It could be also when the parameter is very large and duplicating will be costly. Else we can use pass by reference. If the passed by reference parameter should be protected from accidental change then pass by const-reference could be used. The call by result is a special case in which a parameter is sent only to get a result in a subroutine.

Page 2: parameter-passing modes - sce2.umkc.edusce2.umkc.edu/csee/leeyu/class/CS441/PA/Practice-Test2-Sol.pdf · For the meaning of the ... write a code sample that generates a dangling

c. Give examples in which it is useful to return a reference from a function (e.g., in C++).

void main() ….. int a[]={ 12, 4 ,8 , 1 ,2 ,0} sort( &a,7 ); cout << “ sorted numbers are” <<endl; for( int i =0; i<7;i++) cout<<a[i];<< “\t”; …… void sort( int *a, int count) {

//crude sorting … for(int i=0;i<count -1;i++) for(int j = i+1; j<count; j++) {

If(*(a+i) < *(a+j)) {

//swap ! a = a + b; b = a - b; a = a – b; }

} }

d. Does a program run faster when the programmer leaves optional parameters out of a subroutine call? Why or why not?

The optional parameters are not going to play any role in speeding the program as they are copied on to the stack.

a. Explain the difference between a coroutine and a subroutine. Explain the difference between a coroutine and a thread. What was the first high-level programming language to provide coroutines?

Suggested Solution:

Ref: http://www.akira.ruc.dk/~keld/research/COROUTINE/COROUTINE-1.0/DOC/COROUTINE_REPORT.pdf

A subroutine is the one which halts when it make a call to another subroutine and will resume after the called subroutine ends. But in a co routine the

Page 3: parameter-passing modes - sce2.umkc.edusce2.umkc.edu/csee/leeyu/class/CS441/PA/Practice-Test2-Sol.pdf · For the meaning of the ... write a code sample that generates a dangling

routines halt and proceed alternatively. It is better explained in the following figure

SIMULA was the first language to support it.

2. Given the following simple assignment statement in Java

a = b + c

The statement contains the following components: • Identifies: a, b, c • Operators: =, +

For each component of the statement, list the various bindings that are required to determine the semantics when the statement is executed. For each binding, indicate the binding time used for the language. Explain your answer.

Suggested Solution: For a, b .c:

Type: compiler time binding Address: if static, loading time binding, otherwise runtime binding Value: runtime binding Scope: compiler time binding since Java uses static scoping Life time: if static, same as the program; if instant variables, same

as the object; if local variables of a method, as long as a method call.

For the meaning of the = assignment operator:

Language design time binding For the meaning of the + operator:

Compiler time binding to sum or concatenation.

Page 4: parameter-passing modes - sce2.umkc.edusce2.umkc.edu/csee/leeyu/class/CS441/PA/Practice-Test2-Sol.pdf · For the meaning of the ... write a code sample that generates a dangling

3. Explain why dynamic type bindings is closely related to implicit heap-dynamic variables, using the following code example:

var a; …. a = “Hello”; …. a = 123.456;

Suggested Solution: Variable a gets its type at runtime, i.e. dynamic type binding, when a value is assigned to it. Since variable a may often change the types of values it holds, hence the memory locations where the values are store, a must be a reference variable and its dynamically assigned value must be in a dynamically allocated memory location, i.e. the heap.

4. Given the following Java-like code, what is the output of the program when each of the following scoping rules is applied? Explain your answers.

a. Static scope b. Dynamic scope

public class A { int x = 0; void fa() {

int x = 1; fb();

} void fb() {

println("x = " + x) } public static void main(String[] args) {

new A().fa(); }

}

Suggested Solution o Static Scope: The output is 0, since the variable x is declared as an instant variable

of class A which is initialized to 0. o Dynamic Scope: The output is 1, since the local variable x of method fa() is closer

to the method fb() on the system stack when the prinln() statement is executed at runtime

Page 5: parameter-passing modes - sce2.umkc.edusce2.umkc.edu/csee/leeyu/class/CS441/PA/Practice-Test2-Sol.pdf · For the meaning of the ... write a code sample that generates a dangling

5. Consider the following skeletal C program.

void fun1(void) { int b, c, d; // call another function

} void fun2(void) {

int c, d, e; // call another function

} void fun3(void) {

int d, e, f; // call another function

} void main () {

int a, b, c; // call another function

}

Given the following calling sequences and assuming that dynamic scoping is used, what variables are visible during execution of the last function called? Include with each visible variable the name of the function in which it was defined.

a. main calls fun1; fun1 calls fun2; fun2 calls fun3. b. main calls fun1; fun1 calls fun3. c. main calls fun3; fun3 calls fun1. d. main calls fun3; fun3 calls fun2; fun2 calls fun1.

Suggested Solution

a. d, e, f: fun3; c: fun2; b: fun1; a: main b. d, e, f: fun3; b, c: fun1; a: main c. b, c, d: fun1; e, f: fun3; a: main d. b, c, d: fun1: e: fun2; f: fun3; a: main

6. Pointer and reference type

(a) For a language with which you are familiar that provides a pointer type for programmer-constructed data objects and operations such as new and delete (or similar), which allocate and free storage for objects, write a code sample that generates garbage (i.e., useless objects that keep occupying memory space). Then, write a code sample that generates a dangling reference.

Suggested Solution:

Page 6: parameter-passing modes - sce2.umkc.edusce2.umkc.edu/csee/leeyu/class/CS441/PA/Practice-Test2-Sol.pdf · For the meaning of the ... write a code sample that generates a dangling

(b) In your selected language, suggest programming techniques that could diminish the risk of generating garbage and dangling references. What language constructs in your selected language can be used to support your techniques (if any)?

C# is one such language which does automatic garbage collection. It is based on a usage approach that the unreferenced space and not usable space are freed up.

Further reading: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/dotnetGCbasics.asp

7. Two standard parameter passing mechanisms, pass-by-reference and pass-by-value-result, are very similar but may produce differing results in the presence of aliases. Give an example showing such a situation.

Suggested Solution

Most of the time call-by-reference and call-by-value/result appear to be the same. Let's say we have a function:

void f( int a, int b ) { a = 1; b = 2; }

If we call this function with a single argument like this: int x = 10; f( x, x ); //what is the value of x now? then inside the function body, a and b are ALIASES for x.

Page 7: parameter-passing modes - sce2.umkc.edusce2.umkc.edu/csee/leeyu/class/CS441/PA/Practice-Test2-Sol.pdf · For the meaning of the ... write a code sample that generates a dangling

With call-by-reference, altering a or b actually alters x so the value of x is simply the LAST value assigned, in this case 2. With call-by-value/result, the value of x is copied into two distinct locations (locals a and b). The first assignment changes the value of the local a, the second changes the value of the local b. Then, as part of the function return, the locals are COPIED BACK into the actuals. So the value of x depends on the ORDER in which the locals are COPIED BACK. If a is copied first, then b, the final value is 2, the same as with call-by-reference. BUT if the b is copied first, then a, the final value is 1, which is different from call-by-reference.

8. Turns out, it is IMPOSSIBLE to implement a swap procedure using call-by-name parameter passing that handles the following two calls correctly (one of them will always produce incorrect results):

swap( i, a[i] ); swap( a[i], i );

Explain. Suggested solution: Call-by-name is essentially macro-substitution. Each occurrence of the formal in the body of the function is replaced, textually, by the actual expression. Here's what swap looks like:

swap( int a, int b ) { int tmp = a; a = b; b = tmp; }

Rewritten, the first call above is effectively: int tmp = i; i = a[i]; a[i[ = tmp;

The problem is in line 3. tmp is being assigned to a DIFFERENT element of the array because i has changed! You can make the first call work by rearranging the order of assignments but then the second call doesn't work. This strange consequence of call-by-name was described in a paper published soon after the language was introduced.

9. Some C puzzles involving expression evaluation and assignment: a. What happens if you submit this code to a C compiler? Does it compile? If so,

what does mean? int x=10, y; y = ++x++; printf( "%d\n", y );

Page 8: parameter-passing modes - sce2.umkc.edusce2.umkc.edu/csee/leeyu/class/CS441/PA/Practice-Test2-Sol.pdf · For the meaning of the ... write a code sample that generates a dangling

Suggested solution: This will produce a syntax error. A quick glance might suggest that x is incremented twice but it is more subtle than that. The ++ operator is interesting because it must be applied to an l-value but it yields an r-value. ++ is right associative in the C family so the compiler tries to parse the expression as:

y = ++(x++); It is not possible to increment the result of an increment operation on an int.

a. What's the problem here? int y; double x, z; x = y = z = 3.1415;

Suggested solution:

There is a hidden truncation lurking in here. Because = is right associative, first 3.1415 is assigned to z, then the same value is assigned to the int y, causing a truncation. This truncated value (3.0) is then assigned to the floating-point variable x.