Pointers References and Back in C++

Posted in software by Christopher R. Wirz on Thu Jan 28 2016



A C style API is often written in terms of a mix of pointers and references in functions that return void or status. Passing an argument by reference or by pointer both enable the passed argument to be changed by the function.

Pass-by-reference is more efficient than pass-by-value, because it does not copy the arguments. When the called function read or write the formal parameter, it is actually read or write the argument itself.

Pass-by-pointer passes the memory address by value, but not the value at the address. Since a copy (even if it is a copy of a pointer is made) it is a little less efficient. A nice side effect is that the value at the memory address does not have to be initialized. It can be NULL!

References are generally implemented using pointers. A reference must refer to an object or value. References cannot be NULL, but pointers can.

While this isn't groundbreaking, the following example shows that even stack-allocated variables can be passed (in and out) as pointers or by reference without data loss.


#include <iostream>

using namespace std;

void function_using_reference(int& y, int& m, int& d, std::string& timeString){
    y = 2016;
    m = 1;
    d = 28;
    timeString = "2016-01-28";
}

void pointer_to_ref_function(int* y, int* m, int* d){
    std::string s;
    function_using_reference(*y, *m, *d, s);
}

void ref_to_pointer_function(int& y, int& m, int& d) {
    pointer_to_ref_function(&y, &m, &d);
}

int main()
{
    int y=0, m=0, d=0;
    pointer_to_ref_function(&y, &m, &d);
    cout<<"y  = " << y << "\n";
    cout<<"m  = " << m << "\n";
    cout<<"d  = " << d << "\n";
    cout << "Pointer to reference checks\n\n";

    // create completely new values to check again
    int y2=0, m2=0, d2=0;
    ref_to_pointer_function(y2, m2, d2);
    cout<<"y2 = " << y2 << "\n";
    cout<<"m2 = " << m2 << "\n";
    cout<<"d2 = " << d2 << "\n";
    cout << "And so does reference to pointer to reference\n\n";

    return 0;
}

The output of this code is as follows:


y  = 2016
m  = 1
d  = 28
Pointer to reference checks

y2 = 2016
m2 = 1
d2 = 28
And so does reference to pointer to reference

While pointers seem useful for situations in which the value is initialized by the method, passing by reference is more efficient. Try it out for yourself. Run this example online.

Looking for a job?