What is the difference between a value and reference parameter?

label Computer Science
account_circle Unassigned
schedule 1 Day
account_balance_wallet $5

  • What is the difference between a value and reference parameter?
Sep 16th, 2014

call by value: send the  function a copy of argument's value .

e.g

int foo( int a)

{

a = a+1; return a;

}

// basically change in value does not reflect in call by value

//

int main()
{
   int xx = 0;
   cout << f(xx) << ′\n′;   //print on screen 1
   cout << xx << ′\n′;    // print on screen  0; f() doesn’t change xx
   int yy = 7;
   cout << f(yy) << ′\n′; // print on screen 8;  f() doesn’t change yy
   cout << yy << ′\n′;    // print on screen 7
}

// we can see here that value of xx does not change

if we pass the value to same program by reference then value of x will change

int f(int& a) {

a = a+1; return a;

}

int main()
{
   int xx = 0;
   cout << f(xx) << ′\n′;   //print on screen 1
   cout << xx << ′\n′;    // print on screen  1; f() does change xx
   int yy = 7;
   cout << f(yy) << ′\n′; // print on screen 8;  f() doesn change yy
   cout << yy << ′\n′;    // print on screen 8
}

In call by reference value of variable also change mean change in function also reflect in main function.


Sep 16th, 2014

Did you know? You can earn $20 for every friend you invite to Studypool!
Click here to
Refer a Friend
...
Sep 16th, 2014
...
Sep 16th, 2014
Jun 28th, 2017
check_circle
Mark as Final Answer
check_circle
Unmark as Final Answer
check_circle
Final Answer

Secure Information

Content will be erased after question is completed.

check_circle
Final Answer