The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+13 votes
2.2k 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
asked in Programming by Loyal (6.1k points)
retagged by | 2.2k views

2 Answers

+23 votes
Best answer

(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]
}



A very good read: http://courses.cs.washington.edu/courses/cse341/03wi/imperative/parameters.html

answered by Veteran (352k points)
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
–1 vote
(a) passing a constnt value as parameter

(if any mistake in my ans plz correct it)
answered by (31 points)
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.

Related questions



Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

37,072 questions
44,643 answers
127,045 comments
43,699 users