Const pointer is a pointer that can’t change the address of the variable that is pointing to.
Once const pointer is made to point one variable, we can’t change this pointer to point to any other variable. This pointer is called const pointer.
A const pointer is a pointer whose address cannot be changed after initialization.
In other words, once a const pointer is made to point to a particular variable, it cannot be
made to point to another variable. However, the value stored at the pointed location can still
be modified (if the data itself is not declared as const).
data_type * const pointer_name = &variable;
Example:
int num = 10;
int * const ptr = #
Here, ptr is a const pointer. It must always point to num and cannot
be assigned the address of another variable.
#include
int main() {
int num = 10;
int * const ptr = #
*ptr = 20; // Allowed
printf("Value of num = %d\n", num);
return 0;
}
In this example, the value of num is changed through the pointer. This is allowed
because the data is not constant.
#include
int main() {
int num1 = 10;
int num2 = 20;
int * const ptr = &num1;
ptr = &num2; // Error
return 0;
}
The above statement generates a compilation error because a const pointer cannot be made to point to a different memory address after initialization.
* const.| Feature | Const Pointer | Pointer to Const |
|---|---|---|
| Declaration | int * const ptr |
const int *ptr |
| Can Change Address? | No | Yes |
| Can Modify Value? | Yes | No |
num = 10
+------+ +------+
| num | <---- | ptr |
+------+ +------+
ptr always points to num
A const pointer is a pointer whose address cannot be changed after it is
initialized. It always points to the same memory location, although the value stored at that
location can be modified unless the data itself is declared as const.