C++ : Pointers with Functions

03-11-17 Course- CPP

Passing Argument by Reference

In function chapter, you learned about passing arguments to a function. This is pass by value because actual value is passed. There is another way of passing argument in which actual value is not passed, only the reference to that value is passed. Consider this example:


#include <iostream>
using namespace std;

int main() {
    void swap(int&, int&);      // Function prototype

    int a = 1, b = 2;
    cout << "Before swapping" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    swap(a, b);

    cout << "\nAfter swapping" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    return 0;
}

void swap(int& n1, int& n2) {
    int temp;
    temp = n1;
    n1 = n2;
    n2 = temp;
}

Output


Before swapping
a = 1
b = 2

After swapping
a = 2
b = 1

In main(), two integer variables are defined. And those integers are passed to a function swap() by reference. Compiler can identify this is pass by reference because function definition is void swap(int& n1, int& n2) (notice the & sign after data type). Here, n1 and n2 are the different names given to the argument passed, that is n1 and a is exact same variable (not only their value is same but both name refer to one single variable). Similarly, n2 and b is exact same variable.

There is another way of doing this same exact task using pointers. Consider this example:


#include <iostream>
using namespace std;

int main() {
    void swap(int*, int*);      // Function prototype

    int a = 1, b = 2;
    cout << "Before swaping" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    swap(&a, &b);

    cout << "\nAfter swaping" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    return 0;
}

void swap(int* n1, int* n2) {
    int temp;
    temp = *n1;
    *n1 = *n2;
    *n2 = temp;
}

The output of this example is same as before. In this case, the address of variable is passed during function call rather than variable itself.


swap(&a, &b); // &a is address of a 
and &b is address of b

Since the address is passed instead of value, dereference operator must be used to access the value stored in that address.


void swap(int* n1, int* n2) { 
 ... .. ...
}

The *n1 and *n2 gives the value stored at address n1 and n2 respectively.

Since n1 contains the address of a, anything done to *n1 changes the value of a in main() function as well. Similarly, b will have same value as *n2.