2.7k 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 | 2.7k 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
+3

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.

0
@ 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??
+1
Shouldn't i be used as global variable.
0

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
0

Sir passing an Array can also lead to different value.

Fun1(int *A[])

{

*(A+i)=k;

}

Fun2(int P[])

{

P[i]=k;

}

main(){ int B[n]

Fun2(B);//[it wil not effect array at all]

Fun1(B)//[it will change B[i]=k;]

}

Correct me what i m thinking wrong if any?

0

@, in question it is saying for call by name means formal parameter will replace by actual parameter so in Fun2 in your example when you'll pass 'B' then array P will be replaced by B so in that case both will generate the same output.

–1 vote
(a) passing a constnt value as parameter

(if any mistake in my ans plz correct it)
0
Passing a constant value will produce the same result in both these parameter passing mechanisms or in almost any of the parameter passing mecahinsms.

1
2