When to Use Pointers over References

In what situations should I use pointers instead of references in C++?

While references are generally preferred in modern C++, there are still situations where pointers are necessary or more appropriate:

  1. When you need to represent the absence of a value. A pointer can be null, while a reference must always refer to an object.
  2. When you need to change what a pointer points to. References cannot be reassigned after initialization.
  3. When you need to do arithmetic on the address. Pointer arithmetic is not possible with references.
  4. When interfacing with legacy code that uses pointers.

Here's an example where a pointer is used to represent the absence of a value:

#include <iostream>

void Print(const int* ptr) {
  if (ptr) {
    std::cout << "Value: " << *ptr << "\n";
  } else {
    std::cout << "Null pointer\n";
  }
}

int main() {
  int x = 10;
  int* ptr1 = &x;
  int* ptr2 = nullptr;

  Print(ptr1);
  Print(ptr2);
}
Value: 10
Null pointer

Understanding Reference and Pointer Types

Learn the fundamentals of references, pointers, and the const keyword in C++ programming.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Passing References to const
Why should I pass references to const when a function does not modify its arguments?
Const Pointers and Pointers to Const
What is the difference between a const pointer and a pointer to const?
Reference and Pointer Performance
Is there a performance difference between using references and pointers in C++?
Passing and Returning References
What should I be aware of when passing or returning references in C++?
Pointer to Pointer Use Cases
In what situations would I need to use a pointer to a pointer in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant