C++ – References & Pointers in functions

Hello again!

Today I am going to explain how to use references and pointers during our programming.

First of all advantages & disadvanteges:

A:

– we don’t create a copy of our arguments, we work only on a reference or pointer

– faster realization and faster compilation in comparison to transfer args through values

-we can return a lot of values

D:

– more difficult to learn it and more difficult to use it

We are after a short introduction, so go on:


/*Using references

by Maciej Jędrzejewski*/
 #include <iostream>


using namespace std;

void sum(int &, int &); //here we declare function with references  ( "&" operator)


int main()

{

int a,b;

cout << "Insert a: " << endl;

cin >> a;

cout << endl;


cout << "Insert b:" << endl;

cin >> b;

cout << endl;


sum(a,b);


return 0;

}

void sum(int &rA, int &B) //here is a definition of our function

{

cout << rA + rB << endl;

}


Then, pointers


/*Using pointers
*
*by Maciej Jędrzejewski*/

#include <iostream>


using namespace std;

void sum(int *pA, int *pB); //here we declare function with references  ( "&" operator)


int main()

{

int a,b;

cout << "Insert a: " << endl;

cin >> a;

cout << endl;


cout << "Insert b:" << endl;

cin >> b;

cout << endl;


sum(&a,&b); // as you can see, we have to add & operator to our variables, first disadvantage of using pointers


return 0;

}

void sum(int *pA, int *pB) //here is a definition of our function

{

cout << *pA + *pB << endl;  // and here there is a second disadvantage - because pointer "drives" us to variable, we have to use *operator to get a value which is under our pointer!

}


As you can see I use prefix, when I write reference or pointer. For pointer it is „p” and for reference it is „r”, but it is not necessary, it is just my own custom style.

What to use? I am sure that all of you will answer that it is 1st option – references. These are easier, better to remember. And you are right, those cases in which you can use reference – use it instead of pointers. Of course, there are few of situations, where pointers are irreplaceable, but for more informations you have to wait for the next article.

Zostaw komentarz

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Wyloguj /  Zmień )

Zdjęcie na Google+

Komentujesz korzystając z konta Google+. Wyloguj /  Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj /  Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj /  Zmień )

w

Connecting to %s