recategorized by
1,749 views
5 votes
5 votes

Consider the procedure declaration:

Procedure
P (k: integer)

where the parameter passing mechanism is call-by-value-result. Is it correct if the call, P (A[i]), where A is an array and i an integer, is implemented as below.

  1. create a new local variable, say z;
  2. assign to z, the value of A [i];
  3. execute the body of P using z for k;
  4. set A [i] to z;

Explain your answer. If this is incorrect implementation, suggest a correct one.

recategorized by

1 Answer

7 votes
7 votes
The given implementation is correct.

In call-by-value-result parameter passing mechanism, formal parameter gets its initial value from the actual parameter being passed. During execution of the function, there is no effect on the actual argument but once the function is returned, the final value of the parameter is copied back to the actual parameter. And this is exactly what the given implementation does.

This is different from call-by-reference in the sense that there whatever modification happens to the parameter in a function, it must reflect in the actual argument too. These two can produce different outputs if a global variable is being used as a parameter.

Related questions

22 votes
22 votes
3 answers
4