Easy Tutorial
❮ Programmer 520 Nginx Setup Intro ❯

The Differences Between Pointers and References in C++

Category Programming Techniques

Comparison of References and Pointers in C++

References are a concept in C++, and beginners often confuse references with pointers.

In the following program, n is a reference to m, and m is the referent.

int m; 
int &n = m;

n is equivalent to an alias (nickname) for m; any operation on n is an operation on m.

Thus, n is neither a copy of m nor a pointer to m; in fact, n is m itself.

Rules of references:

In the following example program, k is initialized as a reference to i.

The statement k = j does not change k to a reference to j; it only changes the value of k to 6.

Since k is a reference to i, the value of i also becomes 6.

int i = 5; 
int j = 6; 
int &k = i; 
k = j; // Both k and i are now 6;

The main function of a reference is to pass arguments and return values in functions.

In the C++ language, there are three ways to pass arguments and return values in functions: pass by value, pass by pointer, and pass by reference.

The following is an example of "pass by value."

Since the x inside the Func1 function is a copy of the external variable n, changing the value of x does not affect n, so the value of n remains 0.

void Func1(int x) 
{ 
    x = x + 10; 
} 
... 
int n = 0; 
Func1(n); 
cout << "n = " << n << endl; // n = 0

The following is an example of "pass by pointer."

Since the x inside the Func2 function is a pointer to the external variable n, changing the content of this pointer will cause the value of n to change, so the value of n becomes 10.

void Func2(int *x) 
{ 
    (* x) = (* x) + 10; 
} 
... 
int n = 0; 
Func2(&n); 
cout << "n = " << n << endl; // n = 10

The following is an example of "pass by reference."

Since the x inside the Func3 function is a reference to the external variable n, x and n are the same thing; changing x is equivalent to changing n, so the value of n becomes 10.

void Func3(int &x) 
{ 
    x = x + 10; 
} 
... 
int n = 0; 
Func3(n); 
cout << "n = " << n << endl; // n = 10

Comparing the three example programs above, you will find that "pass by reference" has the properties of "pass by pointer," but the syntax is similar to "pass by value."

In fact, anything that can be done with a "reference" can also be done with a "pointer." So why do we need "references"?

The answer is "to use the right tool for the right job."

Pointers can operate on anything in memory without restrictions, and although pointers are powerful, they are very dangerous.

If you only need to borrow an "alias" of an object, use a "reference" instead of a "pointer" to avoid accidents.

❮ Programmer 520 Nginx Setup Intro ❯