yjc
yjc

Reputation: 11

Will call by name affect the argument variables passed into the function like called by reference or is it like call by value?

Suppose I have an integer array a

a[0] = 1
a[1] = 2
a[2] = 3

and a function in no particular language

func swap(int l, int r){
  int temp = l;
  l = r;
  r = temp;
}

What is my final value of array a if I execute

int i = 1;
swap(i,a[i]);

in call by value, call by reference and call by name?

I think that call by value would give me the same integer array a = [1,2,3] as changes within the function has no effect to the arguments passed in.

and call by reference would give me the result a = [1,1,3], so what about call by name? Can you show me the steps of the evaluation, I only know that it will pass in the i and a[i] directly into the function call so far but have no ideas what would be affected.

Edit: I have misread the question and array a is supposed to be a = [1,2,3] initially rather than a= [10,20,30]

Upvotes: 1

Views: 46

Answers (1)

user13463803
user13463803

Reputation: 291

I'm not aware of any language that has implemented "call by name" since Algol 60 (and possibly a few close derivatives in that era).

But the way to figure it out on paper is:

(1) write out the text of 'swap'.

(2) replace every occurrence of the formal parameter 'l' by the actual argument 'i'.

(3) replace every occurrence of the formal parameter 'r' by the actual argument 'a[i]'.

(4) evaluate the resulting code.

(This would require a little more explanation if there were name clashes, but there aren't)

Steps 1 through 3 get you this code, commented as to the evaluation.

  int temp = i;  // temp = 1
  i = a[i];      // i = a[1] = 20
  a[i] = temp;   // a[20] = 1

The last line looks like an array bounds violation.

The difference between this and the by-reference case is this: with by-reference, for a[i] we determine prior to the call that the actual argument is a[1], and pass a reference to that single element. Changes to the value of i after that do not affect what is referenced. But with call-by-name, what the argument refers to is recalculated each time the argument is used, so it always depends on the value of i right there and then.

(Implementationally, the argument a[i] is passed as a pointer to a little piece of code -- called a 'thunk' -- that will compute the address of a[i])

Upvotes: 1

Related Questions