Friday, November 6, 2015

c++ call by reference vs call by value

c++ call by reference vs call by value

 lets say that you create a int variable call "a".
 you store a value 1.

In c++ syntax, it would be  " int a = 1 "
For sake of simplity, lets think that your code will stay in memory (RAM) when you run it (I think it is true ).
In one section of memory, your int a is like below

 Your int can be any where in the memory (not true... but let's make it simple. It is almost true), there is gotta be some way to keep tract where your a is in the memory. Otherwise, you do not grab the variable when you need it.
For this reason, when you create a variable, you are actually create two thing. One is what you assign to the variable. The other one is address which is create by the computer ( i think it is by compliler or operating system.. not sure hahahah).

That strange number, 0x7ff58d72bac is the address.

Using these two information, we can do call by reference and call by variable.

Call by value function uses the value of variable.
Call by reference function uses the address of variable.

How can I get the address of variable, there are couple ways...
One way is using operator &.

after declare and initialize the variable, put & ahead of variable name like below

int a =1;
cout << &a << endl;

In below coding I made simple programming that can show you call by value and call by reference.

----------------------------------------------------------------------------------------------------------------------------
The following is practice code. If you have suggestion or correction, please feel free to leave comment.

#include <iostream>

using namespace std;

// call by value
int callByVal( int a )  ;

// call by reference
void callByRef( int & a );

int main()
{
     int a = 1;
     cout << "original a : "<< &a << endl;    
   
     // call by value
     // the function make a copy of a in main
     // the coped value is stored a in callByVal function
     // the function do the calculation
     // return the calculate value to a in main
     // a copy the value
     // a in main and a in callByVal are different
     // if you see the addresses of these two, you can see that they are different
     a = callByVal( a );

     // call by referenece
     // the function takes main a's address
     // by having the a's address, calByRef function knows where the a is in the memory
     // callByRef function uses the main's a to do calculation
     // a in main and a in callByRef are identical
     // if you see the address of these two, you can see that they are same
     callByRef( a );

     // a = 1 + 1 + 2
     cout << "1+1+2 = " << a << endl;
}

int callByVal( int a )
{
    cout << "address of a in call by value " << &a << endl;
    return a + 1;
}

void callByRef( int &a )
{
    cout << "address of a in call by reference" << &a << endl;
    a +=  2;
}




No comments:

Post a Comment