Constant Pointer:-
It is type of pointer whose address cannot be modified after first time initialization.
Ex:-
#include<stdio.h>
int main()
{
int var = 10, var2 = 20;
int *const ptr = &var;
ptr = &var2; /* error cant change read only ptr is constant*/
*ptr = 30; /* value can be changed */
printf(“ptr = %d\n”,*ptr);
return 0;
}
In this program ptr is constant which cannot hold the other addresses but value can be modified.
Pointer to a constant:-
It is type of pointer in which the data pointed cannot be modified.
Ex:-
#include<stdio.h>
int main()
{
int var = 10, var2 = 20;
const int* ptr = &var;
ptr = &var2; /* can change the address */
*ptr = 30; /* error data is constant */
printf(“ptr = %d\n”,*ptr);
return 0;
}
In this program ptr points to constant data which cannot be modified,but address can be modified.
Constant pointer to a constant:-
This is combination of above to here data and address are constants.
Ex:-
#include<stdio.h>
int main()
{
int var = 10, var2 = 20;
const int* const ptr = &var;
ptr = &var2; /* error address is constant */
*ptr = 30; /* error data is constant */
printf(“ptr = %d\n”,*ptr);
return 0;
}
Easy way to remember:-
const int * ptr :- if * comes after const then data is constant.
int * const ptr :- if * comes before const then address is constant.
cons int * const ptr :- address and data both are constant.
Comments