Explain "passing by value", "passing by pointer" and "passing by reference"

Questions by suji   answers by suji

Showing Answers 1 - 2 of 2 Answers

rahultripathi

  • Sep 24th, 2005
 

There  is major defference between these three are when we want to avoid making the copy of variable and we want to change value of actual argument on calling function. there are we use passing by pointer,passing the reference. We can not perform arithmentic operation on reference.

  Was this answer useful?  Yes

pramay

  • Mar 10th, 2006
 

Pass By Value example:

The function receives a copy of the variable. This local copy has scope, that is, exists only within the function. Any changes to the variable made in the function are not passed back to the calling routine. The advantages of passing by values are simplicity and that is guaranteed that the variable in the calling routine will be unchanged after return from the function. There are two main disadvantages. First, it is inefficient to make a copy of a variable, particularly if it is large such as an array, structure or class. Second, since the variable in the calling routine will not be modified even if that's what is desired, only way to pass information back to the calling routine is via the return value of the function. Only one value may be passed back this way.

Consider function void foo(int i);

int j=3;

foo(j);

Pass by Reference example:

C++ provides this third way to pass variables to a function. A reference in C++ is an alias to a variable. Any changes made to the reference will also be made to the original variable. When variables are passed into a function by reference, the modifications made by the function will be seen in the calling routine. References in C++ allow passing by reference like pointers do, but without the complicated notation. Since no local copies of the variables are made in the function, this technique is efficient. Additionally, passing multiple references into the function can modify multiple variables.
Consider function void foo(int& i);

int j=3;

foo(&j);

Pass by Pointer example:

A pointer to the variable is passed to the function. The pointer can then be manipulated to change the value of the variable in the calling routine. The function cannot change the pointer itself since it gets a local copy of the pointer. However, the function can change the contents of memory, the variable, to which the pointer refers. The advantages of passing by pointer are that any changes to variables will be passed back to the calling routine and that multiple variables can be changed.

Consider function void foo(int* i);

int j=3;

int* p=&j;

foo(p);

if you look at pass by ref & pass by pointer it is almost the same but in pass by pointer you can do pointer arithmetic operation whereas in ref you cannot.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions