CSE 428 : Solution of Assignment #3
Question 1
- With call by value the program prints 2
- With call by reference the program prints 4
- With call by value-result the program prints 3
Question 2
- Call by value cannot be used: in call by value the actual parameters are
evaluated at the moment the function is called, so a function with parameters
passed by value is always strict, i.e. the arguments are evaluated even if they
are not needed
- Call by reference cannot be used: in call by reference the actual parameters
need to be variables, so we could not apply the function to generic expressions
Note: Some languages allow to pass by reference actual parameters which are
general expressions. But in that case they are evaluated and the value is stored in
a temporary location at the moment the call is activated. Thus even in this case
the desider effect of non-strictness cannot be obtained (because the parameters
are evaluated even if their value is not needed).
- Call by value-result cannot be used for the same reason:
the actual parameters need to
be variables.
- Call by name can be used: in call by name the actual
parameters can be generic expressions and they are evaluated only when needed,
so we achieve the desired non-strict effect.
- The function can be defined as follows (using a C++like syntax):
bool non-strict-and(bool name b1, bool name b2){
if (b1)
return b2;
else
return false;
}
Question 3
void p(int &x){
int y = x; // y must be a name not used in c
c[y/x]; // c[y/x] represents c where every occurrence of x is replaced by y
x = y;
}
Question 4
Yes, the two commands are equivalent, in the sense that the final value of y will be
the same.
Note however that the final effect is achieved in different ways: in the first
case we add 1 to y by using an alias (x) to the same location.
In the second case we add 1 to y by using a pointer (*x) to the location of y.
Question 5
- Using only declaration of aliases it is not possible to implement call by reference:
even if we define an alias (reference) to the formal parameter, the alias will still
be referring to the local variable, and have no effect on the actual parameter.
- Using pointers is possible to implement call by reference, although we have to
be careful to use the parameters always in a dereferenced way:
void p(int *x){
c[*x/x] // c[*x/x] represents c where every occurrence of x is replaced by *x
}
Furthermore, we must replace any call of the form p(y) by p(&y).