开发者

evaluation strategy examples

Assuming the language supports these evaluation strategies, what would be the result for call by reference, call by name, and call by value?

void swap(int a; int b)
{
   int temp;
   temp = a;
  开发者_如何学Go a = b;
   b = temp;
}

int i = 3;
int A[5];
A[3] = 4;
swap (i, A[3]);


call by value -The changes done inside swap method are not visible after calling the method. ie. after swap (i, A[3]);

i, A[3] values don't get changed.

call by ref: The changes done inside swap method are visible after calling the method. ie. after swap (i, A[3]);

i, A[3] values get exchanged.

if you are using C++ as language then the signature of the method should be changed to reflect the pass by reference:

void swap(int& a, int& b)
{
   int temp;
   temp = a;
   a = b;
   b = temp;
}


If you call swap() by value nothing will happen. If you call it by reference it will actually do the swap.

Pass by value when the goal of your function is to return a value.

Pass by reference when you need to update your parameters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜