Topic 31 of 91 5. C++ Pointers and References Interactive Tutorial

Pointers vs References in C++: Behavior, Syntax, and Use Cases

15 mins read Last updated: 26 Sep 2026 22,900 views

Direct Answer & Core Concept

Pointers and references are two important features of C++ that allow programmers to access and work with existing objects indirectly.

Both can be used to modify variables, pass data to functions, and work with objects without making unnecessary copies. However, they have different syntax, behavior, and use cases.

A pointer stores a memory address, while a reference acts as another name for an existing object.

Understanding the differences between pointers and references helps you write safer, cleaner, and more efficient C++ programs.

Detailed Explanation & Mechanics

1. What Is a Pointer in C++?

A pointer is a variable that stores the memory address of another variable or object.

You can use a pointer to access or modify the value stored at that address.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int number = 100;

    int* ptr = &number;

    cout << "Original value: " << number << endl;
    cout << "Memory address: " << ptr << endl;
    cout << "Value through pointer: " << *ptr << endl;

    return 0;
}

Example output:

main.cpp
Run Online
Original value: 100
Memory address: 0x7ffe1234
Value through pointer: 100

The displayed memory address is illustrative. Actual addresses vary between systems and program executions.

Explanation

  • number stores the integer value 100.

  • &number obtains the address of the variable.

  • ptr stores that address.

  • *ptr accesses the value at the stored address.

Pointer syntax

main.cpp
Run Online
data_type* pointer_name = &variable_name;

Example:

main.cpp
Run Online
int age = 25;
int* ptr = &age;

2. What Is a Reference in C++?

A reference is another name, or alias, for an existing variable.

Unlike a pointer, a reference does not require explicit dereferencing to access the original variable.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int number = 100;

    int& ref = number;

    cout << "Original value: " << number << endl;
    cout << "Reference value: " << ref << endl;

    return 0;
}

Output:

main.cpp
Run Online
Original value: 100
Reference value: 100

Explanation

  • number is the original variable.

  • ref is a reference to number.

  • Both names refer to the same integer object.

  • Changing ref also changes number.

Reference syntax

main.cpp
Run Online
data_type& reference_name = variable_name;

Example:

main.cpp
Run Online
int age = 25;
int& ref = age;

3. Main Differences Between Pointers and References

The most important difference is that a pointer stores an address, while a reference acts as an alias for an existing object.

Comparison table

FeaturePointerReference
MeaningStores a memory addressAlias for an existing object
DeclarationUses *Uses &
InitializationCan be initialized laterMust be initialized when declared
Null stateCan be nullptrNo normal null-reference state
ReassignmentCan point to another objectCannot be reseated
AccessUses * to dereferenceUsed like the original variable
AddressStores an addressRefers to an object's identity
ArithmeticSupported for suitable pointersNot supported
Function parametersCan be passed as pointersCan be passed as references
Optional objectSuitable for representing absence with nullptrNot suitable for a nullable reference
Main useAddress-based operations and optional objectsAliases and direct access to existing objects

4. Syntax Difference Between Pointer and Reference

Pointers and references use different declaration symbols.

Pointer declaration

main.cpp
Run Online
int number = 10;

int* ptr = &number;

Here, ptr stores the address of number.

To access the original value, use:

Reference declaration

main.cpp
Run Online
int number = 10;

int& ref = number;

Here, ref acts as another name for number.

To access the original value, use:

Complete example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int number = 50;

    int* ptr = &number;
    int& ref = number;

    cout << "Using pointer: " << *ptr << endl;
    cout << "Using reference: " << ref << endl;

    return 0;
}

Output:

main.cpp
Run Online
Using pointer: 50
Using reference: 50

Both provide access to the same original variable.

5. Modifying Values Using Pointers and References

Both pointers and references can modify the original variable.

However, their syntax is different.

Example: Modifying through a pointer

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int number = 100;

    int* ptr = &number;

    *ptr = 200;

    cout << number << endl;

    return 0;
}

Output:

The expression *ptr = 200 changes the value stored at the address held by ptr.

Example: Modifying through a reference

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int number = 100;

    int& ref = number;

    ref = 200;

    cout << number << endl;

    return 0;
}

Output:

The expression ref = 200 directly modifies the original variable.

6. Null Pointer vs Reference

One important difference is that pointers can represent the absence of an object, while ordinary valid references must refer to an existing object.

Null pointer example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int* ptr = nullptr;

    if (ptr == nullptr) {
        cout << "Pointer is null" << endl;
    }

    return 0;
}

Output:

A null pointer should never be dereferenced.

Reference example

main.cpp
Run Online
int number = 100;

int& ref = number;

A reference must be initialized with a valid object.

You cannot normally declare a reference and leave it empty.

Important: C++ does not provide a normal nullable reference type. Avoid creating references that outlive the objects they refer to.

7. Reassigning Pointers vs References

Pointers can be reassigned to point to different objects. References cannot be reseated after initialization.

Example: Reassigning a pointer

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int first = 10;
    int second = 20;

    int* ptr = &first;

    cout << *ptr << endl;

    ptr = &second;

    cout << *ptr << endl;

    return 0;
}

Output:

The pointer initially points to first. Later, it points to second.

Example: Assigning through a reference

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int first = 10;
    int second = 20;

    int& ref = first;

    ref = second;

    cout << "First: " << first << endl;
    cout << "Second: " << second << endl;

    return 0;
}

Output:

The reference still refers to first. The assignment copies the value of second into first; it does not change what ref refers to.

8. Passing Pointers and References to Functions

Both pointers and references can be used as function parameters.

The main difference is how the function receives and accesses the original object.

Example: Passing by pointer

main.cpp
Run Online
#include <iostream>
using namespace std;

void updateValue(int* ptr) {
    if (ptr != nullptr) {
        *ptr = 500;
    }
}

int main() {
    int number = 100;

    updateValue(&number);

    cout << number << endl;

    return 0;
}

Output:

The function receives the variable's address and modifies the value through the pointer.

Example: Passing by reference

main.cpp
Run Online
#include <iostream>
using namespace std;

void updateValue(int& value) {
    value = 500;
}

int main() {
    int number = 100;

    updateValue(number);

    cout << number << endl;

    return 0;
}

Output:

The function receives a reference to the original variable and modifies it directly.

Comparison

FeaturePointer parameterReference parameter
Function callupdateValue(&number)updateValue(number)
Parameterint* ptrint& value
Access*ptrvalue
Can represent absenceYes, with nullptrNo normal null state
Null checkMay be requiredNot normally required
Typical useOptional object or explicit pointer interfaceRequired object that may be modified

9. Const Pointers vs Const References

C++ allows you to use const with both pointers and references.

However, the meaning depends on where const appears.

Pointer to a constant value

You can change the pointer's target, but you cannot modify the pointed-to value through it.

Constant pointer

You cannot change the pointer's target, but you can modify the pointed-to value through it.

Constant pointer to a constant value

main.cpp
Run Online
const int* const ptr = &number;

You cannot change the pointer's target or modify the value through it.

Const reference

You cannot modify the original value through this reference.

Comparison

DeclarationChange target?Modify value through it?
int* ptrYesYes
const int* ptrYesNo
int* const ptrNoYes
const int* const ptrNoNo
const int& refCannot be reseatedNo

10. Pointer Arithmetic vs References

Pointers support arithmetic operations when they point into an array.

References do not support pointer arithmetic.

Example: Pointer arithmetic

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40};

    int* ptr = numbers;

    cout << *ptr << endl;

    ptr++;

    cout << *ptr << endl;

    return 0;
}

Output:

The pointer moves from the first element to the second element.

Reference example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30};

    int& ref = numbers[0];

    cout << ref << endl;

    ref = 100;

    cout << numbers[0] << endl;

    return 0;
}

Output:

The reference provides access to the first array element, but it cannot be incremented to refer to the next element.

11. Returning Pointers vs References From Functions

Functions can return pointers or references, but their lifetime requirements are important.

Returning a pointer

main.cpp
Run Online
#include <iostream>
using namespace std;

int* getValue(int& number) {
    return &number;
}

int main() {
    int value = 100;

    int* ptr = getValue(value);

    cout << *ptr << endl;

    return 0;
}

Output:

The function returns the address of an existing object. The object remains alive while main() is using the pointer.

Returning a reference

main.cpp
Run Online
#include <iostream>
using namespace std;

int& getValue(int& number) {
    return number;
}

int main() {
    int value = 100;

    getValue(value) = 500;

    cout << value << endl;

    return 0;
}

Output:

The function returns a reference to the original object.

Important lifetime rule

Never return a pointer or reference to a local variable that is destroyed when the function returns.

Both pointers and references can become dangling when the object they refer to no longer exists.

12. Pointers and References With Classes

Pointers and references are also useful when working with C++ classes and objects.

Example: Using a pointer with an object

main.cpp
Run Online
#include <iostream>
using namespace std;

class Student {
public:
    void display() {
        cout << "Student information" << endl;
    }
};

int main() {
    Student student;

    Student* ptr = &student;

    ptr->display();

    return 0;
}

Output:

The arrow operator (->) accesses a member through a pointer.

Example: Using a reference with an object

main.cpp
Run Online
#include <iostream>
using namespace std;

class Student {
public:
    void display() {
        cout << "Student information" << endl;
    }
};

int main() {
    Student student;

    Student& ref = student;

    ref.display();

    return 0;
}

Output:

A reference is used like the original object, so the dot operator (.) accesses its members.

13. Practical Use Cases of Pointers

Pointers are useful when a program needs explicit control over addresses or optional access to objects.

Common applications include:

  1. Dynamic memory allocation.

  2. Linked lists and tree structures.

  3. Pointer arithmetic and array traversal.

  4. Function callbacks.

  5. Working with APIs that use pointer parameters.

  6. Representing optional objects with nullptr.

  7. Polymorphism through base-class pointers.

  8. Low-level and system programming.

Example: Pointer with dynamic memory

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int* ptr = new int(100);

    cout << *ptr << endl;

    delete ptr;
    ptr = nullptr;

    return 0;
}

Output:

In modern C++, prefer smart pointers such as std::unique_ptr for managing dynamically allocated objects.

14. Practical Use Cases of References

References are useful when you need a direct alias for an existing object.

Common applications include:

  1. Passing arguments to functions without copying.

  2. Modifying original variables through function parameters.

  3. Returning existing objects from functions.

  4. Accessing class objects through aliases.

  5. Using const references for read-only access.

  6. Supporting operator overloading.

  7. Implementing move semantics with rvalue references.

Example: Swapping two values using references

main.cpp
Run Online
#include <iostream>
using namespace std;

void swapValues(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int first = 10;
    int second = 20;

    swapValues(first, second);

    cout << first << endl;
    cout << second << endl;

    return 0;
}

Output:

The function modifies the original variables without returning a separate result.

15. When Should You Use a Pointer or a Reference?

Choosing between a pointer and a reference depends on the requirements of your program.

Use a pointer when:

  • The object may be absent, represented by nullptr.

  • You need to change which object is being referenced.

  • You need pointer arithmetic.

  • You are working with an API that expects a pointer.

  • You need to express explicit address-based behavior.

Use a reference when:

  • An object is required and must already exist.

  • You want to modify an existing variable through a function.

  • You need read-only access through a const reference.

  • You want a simpler alternative to pointer-based function parameters.

  • You need an alias for an existing object.

Quick decision table

RequirementRecommended choice
Required object parameterReference
Optional object parameterPointer
Modify an existing variableNon-const reference
Read a large object without copyingConst reference
Reassign the targetPointer
Traverse array elements through addressesPointer
Access an object through an aliasReference
Represent no objectnullptr pointer

16. Common Mistakes When Using Pointers and References

1. Dereferencing a null pointer

main.cpp
Run Online
int* ptr = nullptr;

// Invalid: *ptr = 100;

Solution: Check that a pointer is valid before dereferencing it.

2. Using an uninitialized pointer

An uninitialized pointer contains an indeterminate value.

Solution: Initialize pointers with a valid address or nullptr.

3. Declaring a reference without initialization

main.cpp
Run Online
int& ref; // Compilation error

Solution: Initialize the reference with a valid object.

4. Trying to reassign a reference

Assigning another variable to a reference changes the original referred-to object; it does not reseat the reference.

Solution: Use a pointer when the target needs to change.

5. Returning a reference to a local variable

The local variable is destroyed when the function ends.

Solution: Return references only to objects with a suitable lifetime.

6. Confusing pointer and reference syntax

Pointers require dereferencing with *, while references are accessed like ordinary variables.

Solution: Practise both forms with small examples.

7. Assuming references guarantee object lifetime

A reference can become dangling if the object it refers to is destroyed.

Solution: Ensure the referenced object outlives every use of the reference.

17. Best Practices for Pointers and References

Follow these practices when working with pointers and references:

  1. Initialize pointers before using them.

  2. Use nullptr to represent an absent object.

  3. Initialize references when declaring them.

  4. Prefer references for required function arguments.

  5. Use const references for read-only access to larger objects.

  6. Use pointers when nullability or reseating is needed.

  7. Avoid returning references or pointers to local variables.

  8. Keep object lifetimes and ownership clear.

  9. Prefer smart pointers for dynamic ownership management.

  10. Choose the simplest interface that clearly expresses your program's requirements.

18. Frequently Asked Questions (FAQs)

Q1. What is the main difference between pointers and references in C++?

A pointer stores a memory address, while a reference acts as another name for an existing object.

Q2. Which is better, a pointer or a reference?

Neither is universally better. References are usually simpler for required objects, while pointers are useful for optional objects, reseating, and address-based operations.

Q3. Can a reference be null in C++?

A valid ordinary C++ reference must refer to an object or function. It does not have a normal nullable state like a pointer.

Q4. Can pointers be reassigned?

Yes. A pointer can be changed to store the address of another compatible object.

Q5. Can references be reassigned?

No. A reference cannot be reseated after initialization. Assigning another value through it modifies the original object.

Q6. Can pointers and references modify original variables?

Yes. A non-const pointer or reference can modify the object it refers to.

Q7. Can a function return a pointer or reference?

Yes. However, the returned pointer or reference must not refer to an object whose lifetime has ended.

Q8. Are references faster than pointers?

There is no general performance rule that references are always faster. Compilers optimize both, and performance depends on the program and generated code.

Q9. Can references be used with arrays?

Yes. References can refer to individual array elements or entire arrays. C++ does not allow ordinary arrays of references.

Q10. What is the difference between a const pointer and a const reference?

A const pointer restricts whether the pointer itself or its pointed-to value can change, depending on its declaration. A const reference prevents modification through that reference.

Runnable Code Example: Pointers vs References in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>

struct Profile {
    int id;
    std::string name;
};

void updateViaPointer(Profile* p) {
    if (p) p->name = "Updated by Pointer";
}

void updateViaReference(Profile& p) {
    p.name = "Updated by Reference"; // Clean syntax, guaranteed non-null
}

int main() {
    Profile user{101, "Original"};

    updateViaPointer(&user);
    std::cout << "Pointer update:   " << user.name << "
";

    updateViaReference(user);
    std::cout << "Reference update: " << user.name << "
";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: When should you prefer references over pointers?

A: Prefer references whenever an argument is mandatory (non-optional/non-nullable) and operator syntax should be natural. Use pointers when an argument is optional (nullable via `nullptr`) or when implementing dynamic data structures (linked lists, trees) that require node rebinding.
Q

Q: Does a reference occupy memory in assembly?

A: In machine code, compilers typically implement references as `const` pointers under the hood, but the optimizer frequently eliminates storage altogether by substituting direct register usage.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Use references for mandatory function parameters and operator overloading.
2. Use pointers (std::unique_ptr or nullptr-capable raw pointers) when "absence of value" is a valid state.
3. Avoid returning pointers or references to local stack-allocated objects.