Starting from:

$30

Homework 6 Solution




(24 pts) Consider the following C program:



void foo()

{

int i;

printf("%d ", i++);

}




void main()

{

int j;




for (j = 1; j <= 10; j++) foo();




}




Local variable i in subroutine foo is never initialized. On many systems, however, variable




appears to “remember” its value between the calls to foo, and the program will print 0 1 2
3456789.




(12 pts) Suggest an explanation for this behavior.



(12 pts) Change the code above (without modifying function foo) to alter this behavior.



(20 pts) Can you write a macro in C that “returns” the factorial of an integer argument (without calling a subroutine)? Why or why not?



(24 pts) Consider a subroutine swap that takes two parameters and simply swaps their values. For example, after calling swap(X,Y), X should have the original value of Y and Y the original value of X. Assume that variables to be swapped can be simple or subscripted (elements of an array), and they have the same type (integer). Show that it is impossible to write such a general-purpose swap subroutine in a language with:



(12 pts) parameter passing by value.



(12 pts) parameter passing by name.



Hint: for the case of passing by name, consider mutually dependent parameters.

(32 pts) Consider the following program, written in no particular language. Show what the program prints in the case of parameter passing by (a) value, (b) reference, (c) value-result, and (d) name. Justify your answer. When analyzing the case of passing by value-result, you may have noticed that there are two potentially ambiguous issues – what are they?



procedure f (x, y, z)

:= x + 1
:= z
:= z + 1



// main i := 1; a[1] := 10;




a[2] := 11




f (i, a[i], i); print (i); print (a[1]); print (a[2]);




(Extra Credit - 10 pts) Does a program run faster when the programmer does not specify values for the optional parameters in a subroutine call?

More products