Pass by refence

In c++, to pass argument from caller to callee we use pass by reference method. In this modification is made both in caller and called. In this case always the value of arguments and parameters is equal????
The content of the passed argument will be the same for the caller and callee when passed by reference.

In other words: The variable that the caller passes to a function by [non const] reference can be modified by the called function. The change remains after the called function returns.
Last edited on
If you use pass by non-const value then any changes done within the function are NOT passed back to the caller.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

void testFunction( int &ref, int value )
{
   ref = 10;
   value = 20;
   cout << "In function, ref = " << ref << "     value = " << value << '\n';
}

int main()
{
   int a = 1, b = 2;
   cout << "Before call, a = " << a << "     b = " << b << '\n';
   testFunction( a, b );
   cout << "After call, a = " << a << "     b = " << b << '\n';
}


Before call, a = 1     b = 2
In function, ref = 10     value = 20
After call, a = 10     b = 2

1
2
3
4
5
6
7
8
9
10
void testFunction( int &ref, int val )
{
  // use ref and val
}

int main()
{
   int a = 1, b = 2;
   testFunction( a, b );
}

Is roughly equivalent to:
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
   int a = 1, b = 2;

   {
      int& ref = a; // ref is a reference to a
      int val = b; // val has a copy of value of b
      // use ref and val
      // what you do to ref you actually do to a, because ref is a reference
      // what you do to val, you do to val
   }
}
Always been fun if you code in difficult different languages.

In C++ the default is to pass by value.

In Fortran the default is to pass by reference.

In Python, it's just ... anarchic!
def testFunction( alist1, alist2, scalar ):
   alist1, alist2[0], scalar = [10], 20, 30
   print( "In function, alist1 = ", alist1, "     alist2 = ", alist2, "    scalar = ", scalar )

a, b, c = [ 1 ], [ 2 ], 3
print( "Before call, a = ", a, "     b = ", b, "    c = ", c )
testFunction( a, b, c )
print( "After call , a = ", a, "     b = ", b, "    c = ", c )


Before call, a =  [1]      b =  [2]     c =  3
In function, alist1 =  [10]      alist2 =  [20]     scalar =  30
After call , a =  [1]      b =  [20]     c =  3


Last edited on
In Pascal it's default by value. You have to use ref with the argument to get pass by reference.

For one version of Basic I used, it depended upon the arguments passed.

 
CALL MYFUNC(A)


would pass A by ref, but:

 
CALL MYFUNC(A + 0)


would pass by value - as A + 0 can't be changed.
Last edited on
In Python, it's just ... anarchic!

Oh, that is worse the "I don't know it at all" view than I had about Python before.

Then again, even C/C++ have the array decays to pointer. (The pointer is obviously passed by value.)
Topic archived. No new replies allowed.