3k 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 | 3k 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;
}

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 is changed to 8 and not a
}
selected by
+4

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 will get changed only if i is global variable.

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

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;
}

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 will get changed
}


In 2nd code only a 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
yes
+1

@, 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.

0

https://stackoverflow.com/questions/838079/what-is-pass-by-name-and-how-does-it-work-exactly

a parameter such as a[i] depends on the current value of i inside the function, rather than referring to the value at a[i] before the function was called

–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.