The Wayback Machine - https://web.archive.org/web/20240917225221/https://www.geeksforgeeks.org/pointers-vs-references-cpp/
Open In App

Pointers vs References in C++

Last Updated : 26 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Pointers, References 

C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. 

On the surface, both references and pointers are very similar as both are used to have one variable provide access to another. With both providing lots of the same capabilities, it’s often unclear what is different between these mechanisms. In this article, I will try to illustrate the differences between pointers and references. 

Pointers: A pointer is a variable that holds the memory address of another variable. A pointer needs to be dereferenced with the * operator to access the memory location it points to. 

References: A reference variable is an alias, that is, another name for an already existing variable. A reference, like a pointer, is also implemented by storing the address of an object. 
A reference can be thought of as a constant pointer (not to be confused with a pointer to a constant value!) with automatic indirection, i.e., the compiler will apply the * operator for you. 

int i = 3; 

// A pointer to variable i or "stores the address of i"
int *ptr = &i;

// A reference (or alias) for i.
int &ref = i;



Differences:  

1. Initialization: A pointer can be initialized in this way: 

int a = 10;
int *p = &a;
// OR
int *p;
p = &a;



We can declare and initialize pointer at same step or in multiple line.

2. While in references,

int a = 10;
int &p = a; // It is correct
// but
int &p;
p = a; // It is incorrect as we should declare and initialize references at single step



NOTE: This difference may vary from compiler to compiler. The above difference is with respect to Turbo IDE. 

3. Reassignment: A pointer can be re-assigned. This property is useful for the implementation of data structures like a linked list, a tree, etc. See the following example: 

int a = 5;
int b = 6;
int *p;
p = &a;
p = &b;



4. On the other hand, a reference cannot be re-assigned, and must be assigned at initialization.

int a = 5;
int b = 6;
int &p = a;
int &p = b; // This will throw an error of "multiple declaration is not allowed"

// However it is valid statement,
int &q = p;



5. Memory Address: A pointer has its own memory address and size on the stack, whereas a reference shares the same memory address with the original variable and takes up no space on the stack.

int &p = a;
cout << &p << endl << &a;



6. NULL value: A pointer can be assigned NULL directly, whereas a reference cannot be. The constraints associated with references (no NULL, no reassignment) ensure that the underlying operations do not run into an exception situation.

7. Indirection: You can have a pointer to pointer (known as a double pointer) offering extra levels of indirection, whereas references only offer one level of indirection. For example, 

In Pointers,
int a = 10;
int *p;
int **q; // It is valid.
p = &a;
q = &p;

// Whereas in references,
int &p = a;
int &&q = p; // It is reference to reference, so it is an error



8. Arithmetic operations: Various arithmetic operations can be performed on pointers, whereas there is no such thing called Reference Arithmetic (however, you can perform pointer arithmetic on the address of an object pointed to by a reference, as in &obj + 5). 

Tabular form of difference between References and Pointers in C++

  References Pointers
Reassignment The variable cannot be reassigned in Reference. The variable can be reassigned in Pointers.
Memory Address It shares the same address as the original variable. Pointers have their own memory address.
Work It is referring to another variable. It is storing the address of the variable.
Null Value It does not have null value. It can have value assigned as null.
Arguments This variable is referenced by the method pass by value. The pointer does it work by the method known as pass by reference.

When to use What

The performances are exactly the same as references are implemented internally as pointers. But still, you can keep some points in your mind to decide when to use what:  

  • Use references: 
    • In function parameters and return types.
  • Use pointers: 
    • If pointer arithmetic or passing a NULL pointer is needed. For example, for arrays (Note that accessing an array is implemented using pointer arithmetic).
    • To implement data structures like a linked list, a tree, etc. and their algorithms. This is so because, in order to point to different cells, we have to use the concept of pointers.

Quoted in C++ FAQ Lite: Use references when you can, and pointers when you have to. References are usually preferred over pointers whenever you don’t need “reseating”. This usually means that references are most useful in a class’s public interface. References typically appear on the skin of an object, and pointers on the inside. 

The exception to the above is where a function’s parameter or return value needs a “sentinel” reference — a reference that does not refer to an object. This is usually best done by returning/taking a pointer, and giving the “nullptr” value this special significance (references must always alias objects, not a dereferenced null pointer). 

Related Article: 
When do we pass arguments as Reference or Pointers? 

 



Previous Article
Next Article

Similar Reads

lvalues references and rvalues references in C++ with Examples
Prerequisites: lvalue and rvalue in C++, References in C++“l-value” refers to a memory location that identifies an object. "r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable. They are declared using the '&amp;' before the name of the variabl
4 min read
Pointers and References in C++
In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a symbolic representation of addresses. They enable
5 min read
C++ | References | Question 1
What is the return value of f(p, p) if the value of p is initialized to 5 before the call? Note that the first parameter is passed by reference, whereas the second parameter is passed by value. int f(int &amp;x, int c) { c = c - 1; if (c == 0) return 1; x = x + 1; return f(x, c) * x; } (A) 3024 (B) 6561 (C) 55440 (D) 161051 Answer: (B) Explanation:
1 min read
C++ | References | Question 6
Which of the following is FALSE about references in C++ (A) References cannot be NULL (B) A reference must be initialized when declared (C) Once a reference is created, it cannot be later made to reference another object; it cannot be reset. (D) References cannot refer to constant value Answer: (D) Explanation: We can create a constant reference th
1 min read
C++ | References | Question 6
Which of the following functions must use reference. (A) Assignment operator function (B) Copy Constructor (C) Destructor (D) Parameterized constructor Answer: (B) Explanation: A copy constructor is called when an object is passed by value. Copy constructor itself is a function. So if we pass argument by value in a copy constructor, a call to copy
1 min read
C++ | References | Question 4
Predict the output of following C++ program. #include&lt;iostream&gt; using namespace std; int &amp;fun() { static int x = 10; return x; } int main() { fun() = 30; cout &lt;&lt; fun(); return 0; } (A) Compiler Error: Function cannot be used as lvalue (B) 10 (C) 30 Answer: (C) Explanation: When a function returns by reference, it can be used as lval
1 min read
C++ | References | Question 6
Output of following C++ program? #include&lt;iostream&gt; using namespace std; int main() { int x = 10; int&amp; ref = x; ref = 20; cout &lt;&lt; &quot;x = &quot; &lt;&lt; x &lt;&lt; endl ; x = 30; cout &lt;&lt; &quot;ref = &quot; &lt;&lt; ref &lt;&lt; endl; return 0; } (A) x = 20 ref = 30 (B) x = 20 ref = 20 (C) x = 10 ref = 30 (D) x = 30 ref = 30
1 min read
Mixed Cell References in MS Excel
Cell: The row and column in Excel together make a cell. We input the value/data(s) in cells of a spreadsheet. There are three types of values that can be entered into the cell. NumbersAlphabeticFormulas Cell reference ​​​​​​is the address or name of a cell or a range of cell is known as Cell reference. It is the combination of column name and row n
3 min read
Can References Refer to Invalid Location in C++?
Reference Variables: You can create a second name for a variable in C++, which you can use to read or edit the original data contained in that variable. While this may not sound appealing at first, declaring a reference and assigning it a variable allows you to treat the reference as if it were the original variable for the purposes of accessing an
2 min read
Default Assignment Operator and References in C++
We have discussed assignment operator overloading for dynamically allocated resources here. In this article, we discussed that when we don't write our own assignment operator, the compiler creates an assignment operator itself that does shallow copy and thus causes problems. The difference between shallow copy and deep copy becomes visible when the
2 min read
References in C++
When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&amp;’ in the declaration. Also, we can define a reference variable as a type of variable that can act as a reference to another variable. '&amp;' is used for signifying the address of a variable
9 min read
Why Can't I Make a Vector of References?
In C++, the Standard Template Library (STL) provides a robust and versatile collection of containers, with std::vector being one of the most commonly used. However, you may encounter an obstacle when trying to create a vector of references. In this article, we are going to look at why you cannot make a vector of references and some ways around it t
4 min read
Near, Far and Huge Pointers in C
In older times, the intel processors had 16-bit registers but the address bus was 20-bits wide. Due to this, the registers were not able to hold the entire address at once. As a solution, the memory was divided into segments of 64 kB size, and the near pointers, far pointers, and huge pointers were used in C to store the addresses. There are old co
4 min read
Program to reverse an array using pointers
Prerequisite : Pointers in C/C++ Given an array, write a program to reverse it using pointers . In this program we make use of * operator . The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer .
4 min read
Difference between pointer to an array and array of pointers
Pointer to an array: Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array. int a[3] = {3, 4, 5 }; int *ptr = a; We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the
4 min read
Features and Use of Pointers in C/C++
Pointers store the address of variables or a memory location. Syntax: datatype *var_name; Example: pointer "ptr" holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through "ptr" int *ptr; Features of Pointers: Pointers save memory space.Execution time with pointers is faster beca
2 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 min read
How many levels of pointers can we have in C/C++
Prerequisite: Pointer in C and C++, Double Pointer (Pointer to Pointer) in CA pointer is used to point to a memory location of a variable. A pointer stores the address of a variable and the value of a variable can be accessed using dereferencing of the pointer. A pointer is generally initialized as: datatype *variable name; This above declaration i
7 min read
Why do we need reference variables if we have pointers
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do w
4 min read
Unusual behaviour with character pointers
In C++, cout shows different printing behaviour with character pointers/arrays unlike pointers/arrays of other data types. So this article will firstly explain how cout behaves differently with character pointers, and then the reason and the working mechanism behind it will be discussed. Example 1: C/C++ Code // C++ program to illustrate difference
5 min read
C++ Modify Pointers
Prerequisite: Pointer in C++ Pointers are an essential part of the C++ language. It allows us to store the memory address of a variable. One thing to note here is that if we change the value that a pointer is pointing to, then the value of the original variable also changes. Now, let's check the approach we are going to use. Approach: In the below
2 min read
How to Declare and Initialize an Array of Pointers to a Structure in C?
Prerequisite: Structure in CArray in C In C language, arrays are made to store similar types of data in contiguous memory locations. We can make arrays of either primitive data types, like int, char, or float, or user-defined data types like Structures and Unions. We can also make arrays of pointers in C language. Today we will learn how to create
8 min read
How to declare a Two Dimensional Array of pointers in C?
A Two Dimensional array of pointers is an array that has variables of pointer type. This means that the variables stored in the 2D array are such that each variable points to a particular address of some other element. How to create a 2D array of pointers: A 2D array of pointers can be created following the way shown below. int *arr[5][5]; //creati
3 min read
C++ Vector of Pointers
Prerequisites Pointers in C++Vectors in C++ Vector of pointers are vectors that can hold multiple pointers. Each pointer within a vector of pointers points to an address storing a value. We can use the vector of pointers to manage values that are not stored in continuous memory. How to Create Vector of Pointers in C++? Similar to any other vector d
6 min read
Passing Pointers to Functions in C
Prerequisites: Pointers in CFunctions in C Passing the pointers to the function means the memory location of the variables is passed to the parameters in the function, and then the operations are performed. The function definition accepts these addresses using pointers, addresses are stored using pointers. Arguments Passing without pointer When we
2 min read
Pointers in Containers in C++ STL
Prerequisites: Pointers in C++Container in STL There are different containers in C++ having their own features where if are adding extra functionality of pointer it will contribute in a different way. Although not all of the containers are useful in this context so let's see a few of the containers which can be helpful. There are 5 containers that
5 min read
Passing Pointers to Functions In C++
Prerequisites: Pointers in C++Functions in C++ Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer. To change the value of any variable in the function we have to pass the address of
4 min read
What are Wild Pointers? How can we avoid?
Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave unexpectedly. Example of Wild PointersIn the below code, p is a wild pointer. C/C++ Code // C program that demonstrated wild pointers int main() { /* wild pointer */ int* p; /* Some unknown memory locatio
2 min read
Why Does C Treat Array Parameters as Pointers?
In C, array parameters are treated as pointers mainly to, To increase the efficiency of codeTo save time It is inefficient to copy the array data in terms of both memory and time; and most of the time, when we pass an array our intention is to just refer to the array we are interested in, not to create a copy of the array. The following two definit
2 min read
Declare a C/C++ function returning pointer to array of integer pointers
Declare "a function with argument of int* which returns pointer to an array of 4 integer pointers". At the first glance it may look complex, we can declare the required function with a series of decomposed statements. 1. We need, a function with argument int *, function(int *) 2. a function with argument int *, returning pointer to (*function(int *
2 min read
Practice Tags :