const qualifier in C/C++ can be applied to the declaration of any variable to specify that its value will not be changed. const
keyword applies to whatever is immediately to its left. If there is nothing to its left, it applies to whatever is immediately to its right.
Pointer to const Int
Syntax to declares a pointer to const int
type. So one can modify ptr itself but the object pointed to by ptr shall not be modified.
// ptr is a pointer to constant int const int* ptr;
Below example shows allowed operation on pointer to constant integer.
const int a = 10; const int* ptr = &a; *ptr = 5; // Wrong ptr++; // Right
const pointer to int
Syntax to declare constant pointer to integer
// ptr is a constant pointer to int int * const ptr;
Below example shows the use of const pointer to int type. You are not allowed to modify ptr but the object pointed to by ptr.
int a = 10; int *const ptr = &a; *ptr = 5; // Right ptr++; // Wrong
const pointer to const int
Syntax to declare constant pointer to constant integer is
// constant pointer to constant integer. const int * const ptr;
For const pointer to const integer, you can neither change the value pointed by ptr nor the pointer ptr.
int a =10, b =20; const int *const ptr = &a; ptr = &b; // illegal statement *ptr = b; // illegal statement