MENU
Question -

What is the difference between call by reference and call by value with respect to memory allocation ? Give a suitable example to illustrate using C+ + code.



Answer -

Call By Value : In call by value method, the called function creates its own copies of original values sent to it. Any changes that are made, occur on the function’s copy of values are not reflected back to the calling function.
Call By Reference : In call by reference method, the called function accesses and works with the original values using their references. Any changes that occur, takes place on the original values and are reflected back to the calling code.
Example:

//using call by reference

#include

void swap(int &, int &);

int main()

{

int a=10,b=20;

swap(a,b);

cout<

return 0;

}

void swap(int &c, int &d)

{

int t;

t=c;

c=d;

d=t;

}

output :

20 10

//using call by value

#include

void swap(int, int);

int main()

{

int a=10,b=20;

swap(a,b):

cout<

return 0;

}

void swap(int c, int d)

{

int t;

t=C;

C=d;

d=t;

}

output:

10 20

Comment(S)

Show all Coment

Leave a Comment

Free - Previous Years Question Papers
Any questions? Ask us!
×