Const Pointers and Pointers to Const

What is the difference between a const pointer and a pointer to const?

The placement of const in a pointer declaration can be confusing, but it's important to understand the difference:

  1. A pointer to const (e.g., const int*) is a pointer that points to a const value. You cannot change the value that the pointer points to, but you can change the pointer itself to point to another value.
  2. A const pointer (e.g., int* const) is a pointer that cannot be changed to point to another value. However, the value that the pointer points to can be changed.

Here's an example:

int main() {
  int x = 10;
  int y = 20;

  const int* ptr1 = &x;
  // Error: cannot change value through ptr1
  *ptr1 = 30; 
  // Okay: can change to point to another value
  ptr1 = &y;

  int* const ptr2 = &x;
  // Okay: can change value through ptr2
  *ptr2 = 30;
  // Error: cannot change to point to another value
  ptr2 = &y; 
}

You can also have a const pointer to a const value (e.g., const int* const), which means that neither the pointer nor the value it points to can be changed.

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?
When to Use Pointers over References
In what situations should I use pointers instead of references in C++?
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