Pointer to Constant In C Language
Categories: C language
A pointer to constant is a pointer through which the value of the variable that the pointer points cannot be changed. The address of these pointers can be changed, but the value of the variable that the pointer points cannot be changed.
Syntax of Pointer to Constant
const <type of pointer>* <name of pointer>
Declaration of a pointer to constant is given below:
const int* ptr;
Let's understand through an example.
First, we write the code where we are changing the value of a pointer
#include <stdio.h>
int main()
{
int a=100;
int b=200;
const int* ptr;
ptr=&a;
ptr=&b;
printf("Value of ptr is :%u",ptr);
return 0;
}
In the above code:
1. We declare two variables, i.e., a and b with the values 100 and 200 respectively.
2. We declare a pointer to constant.
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 'ptr'.