All about C plus plus algorithms!

Tuesday 10 May 2016

What is a Function in C++ (Part II) | Pass and Return by reference



We have already discussed a function with return type int in which we passed parameters by copy. In this section we will discuss passing and returning by reference.

What is a reference?
            A reference in C++ means the address where that object is stored. In C++ we have two sorts of memory i.e. Stack and Heap. Right now, we are only concerned with the Stack.
Every thing that you make is stored somewhere on the stack and has an address. In case you are not familiar with it already you can try it.

int a = 5;
cout << &a;

           & is used to get the address. By doing this, you can see the address of variable of the variable 'a'  which will be a Hexadecimal code.



         
What is passing by Reference?

        Passing by reference means that you give the address of the variable to the function. Important point is that, after passing by reference, if you change its value in the function, it'll be changed in the original place as well i.e. the memory and main() as well. 

How to pass and return by reference? 
       To pass by reference, you only need to make some change in the prototype of the function.

Let's consider this example : We have to make a swap function (for integers). It's code will be like this 

int temp = a;
a = b;
b = temp;
// 'a' and 'b' are the variables passed.

The function's prototype will be like this :

void mySwap(int &a, int &b)

 The function has return type void because we are gonna return by reference. 
Function :
void mySwap(int &aint &b)
{
      int temp = a;
     a = b;
     b = temp;
}

Now, when we change the values of 'a' and 'b'. The program actually goes to their address and change the values so when we use them in main(), their values will be changed.

Main()
{
      int  one = 1;
      int two = 2;
     mySwap(one, two);   //While calling we didn't put &.. coz its not needed here.
     cout << one << endl << two;

      _getch();
}

    That's all for now. :) Remember, you can do both at the same time i.e. returning by reference as well as by copy. 


Thank you for reading. 
Please lemme know if you like it.
Any questions? Comment below. ^^


Share:

0 comments:

Post a Comment

Popular Posts

Blog Archive

Copyright by progrithms.blogspot.com. All Rights Reserved.. Powered by Blogger.

Copyright © Programs and Algorithms | Powered by Blogger

Design by ThemePacific | Blogger Theme by NewBloggerThemes.com