Difference between const int*, int * const and const int * const in C++
Hello everyone! I just started learning C++ and can't figure out the `const` keyword in the context of pointers. I'm looking at three different declarations and getting completely confused:\n\n1. `const int* ptr;`\n2. `int* const ptr;`\n3. `const int* const ptr;`\n\nWhy do they mean different things? Which one allows changing the value the pointer points to, and which one allows changing the pointer itself? I wrote a small example:\n\n```cpp\nint a = 10;\nint b = 20;\n\nconst int* p1 = &a;\n// *p1 = 30; // error if uncommented\np1 = &b; // works\n\nint* const p2 = &a;\n*p2 = 30; // works\n// p2 = &b; // error if uncommented\n\nconst int* const p3 = &a;\n// *p3 = 30; // error\n// p3 = &b; // error\n```\n\nDo I understand correctly that `const` to the left of the asterisk protects the data, and to the right — protects the pointer itself?
No answers yet.
Log in to leave an answer