0 votes
in C Plus Plus by
Explain Pass by Value and Pass by Reference.

2 Answers

0 votes
by

While passing parameters to the function using “Pass by Value”, we pass a copy of the parameters to the function.

Hence, whatever modifications are made to the parameters in the called function are not passed back to the calling function. Thus the variables in the calling function remain unchanged.

Example:

void printFunc(int a,int b,int c)

{

                  a *=2;

                  b *=2;

                  c *=2;

}

 

int main()

 

{

 

                 int x = 1,y=3,z=4;

                 printFunc(x,y,z);

                 cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;

}

Output:

x=1

y=3

z=4

As seen above, although the parameters were changed in the called function, their values were not reflected in the calling function as they were passed by value.

However, if we want to get the changed values from the function back to the calling function, then we use the “Pass by Reference” technique.

To demonstrate this we modify the above program as follows:

void printFunc(int& a,int& b,int& c)

{

                              a *=2;

                              b *=2;

                              c *=2;

}

  int main()

{

                  int x = 1,y=3,z=4;

                  printFunc(x,y,z);

                   cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;

}

Output: 

x=2

y=6

z=8

As shown above, the modifications done to the parameters in the called functions are passed to the calling function when we use the “Pass by reference” technique. This is because using this technique we do not pass a copy of the parameters but we actually pass the variable’s reference itself.

0 votes
by

When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes are made to that object, it doesn’t affect the original value.

When an object is passed by reference, this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places.

Source: github.com/snowdream   

Related questions

0 votes
asked Dec 10, 2020 in JavaScript by SakshiSharma
0 votes
asked Jun 11, 2020 in Python by Robindeniel
...