const Pointer in C Language
Categories: C language
Constant Pointers
A constant pointer in C cannot change the address of the variable to which it is pointing, i.e., the address will remain constant. Therefore, we can say that if a constant pointer is pointing to some variable, then it cannot point to any other variable.
Syntax of Constant Pointer
<type of pointer> *const <name of pointer>;
Declaration of a constant pointer is given below:
int *const ptr;
Let's understand the constant pointer through an example.
#include <stdio.h>
int main()
{
int a=1;
int b=2;
int *const ptr;
ptr=&a;
ptr=&b;
printf("Value of ptr is :%d",*ptr);
return 0;
}
In the above code:
1. We declare two variables, i.e., a and b with values 1 and 2, respectively.
2. We declare a constant pointer.
3. First, we assign the address of variable 'a' to the pointer 'ptr'.
4. Then, we assign the address of variable 'b' to the pointer 'ptr'.
5. Lastly, we try to print the value of the variable pointed by the 'ptr'.
In the above output, we can observe that the above code produces the error "assignment of read-only variable 'ptr'". It means that the value of the variable 'ptr' which 'ptr' is holding cannot be changed. In the above code, we are changing the value of 'ptr' from &a to &b, which is not possible with constant pointers. Therefore, we can say that the constant pointer, which points to some variable, cannot point to another variable.