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:
- 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. - 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.