1.8k views
In which of the following cases is it possible to obtain different results for call-by-reference and call-by-name parameter passing methods?

(a) Passing a constant value as a parameter

(b) Passing the address of an array as a parameter

(c) Passing an array element as a parameter

(d) Passing an array
retagged | 1.8k views

(c) Passing an array element as a parameter is the answer.

Consider this function call

{
....
a[] = {0,1,2,3,4};
i = 0;
fun(a[i]);
print a[0];
}

fun(int x)
{
int i = 1;
x = 8;
}

Output:
call-by-reference: 8
call-by-name: 0

In Call-by-name, each occurence of the formal parameter is replaced by the actual argument text. So, the function fun will be executed like:

{
int i = 1;
a[i] = 8; //a[1] is changed to 8 and not a[0]
}
selected by

Sir, I have a doubt please see-
I am  not sure please verify if i am thinking right or not.

Here, in this example a[1] will get changed only if i is global variable.

main()
{
....
a[] = {0,1,2,3,4};
i = 0;
fun(a[i]);
print a[0];
}

fun(int x)
{
int i = 1;
x = 8; // The argument expression (a[i]) is re-evaluated, and i refers to the value of i which is in main(), not the i which is here.
}

In case if code have been like this :-

int i = o;
main()
{
....
a[] = {0,1,2,3,4};
fun(a[i]);
print a[0];
}

fun(int x)
{
i = 1;
x = 8;  // The argument expression (a[i]) is re-evaluated, and i refers to the global value which is changed now, so a[1] will get changed
}


In 2nd code only a[1] should be changed not in first one.

@ arjun sir, same thing happens for expressions also, they give different results because in call by name expression will be reevaluated in the function body?? Am i right??
Shouldn't i be used as global variable.

yes it should be global.

 begin
integer n;
procedure p(k: integer);
begin
print(k);
n := n+10;
print(k);
n := n+5;
print(k);
end;
n := 0;
p(n+1);
end;


Output:

call by value:     1  1  1
call by name:      1 11 16
–1 vote
(a) passing a constnt value as parameter

(if any mistake in my ans plz correct it)