What is constant pointer?
C provides const keyword which can change the behaviour of the pointers
It can be used to restrict two operations
1. Don't allow to change the address in the pointer variable
2. Don't allow to change the value at the address
Syntax for fixing the address
datatype * const variable=address;
Syntax for fixing the value
datatype const * variable=address;
or
const datatype * variable=address;
Example 1
main()
{
int a=5,b=6;
int * const p=&a; //addresses if now fixed
*p=2;
p=&b; //error
*p=3;
printf("%d %d",a,b);
}
Example 2
main()
{
int a=5,b=6;
int const * p=&a;
//*p=2;
p=&b;
*p=3;
printf("%d %d",a,b);
}
It can be used to restrict two operations
1. Don't allow to change the address in the pointer variable
2. Don't allow to change the value at the address
Syntax for fixing the address
datatype * const variable=address;
Syntax for fixing the value
datatype const * variable=address;
or
const datatype * variable=address;
Example 1
main()
{
int a=5,b=6;
int * const p=&a; //addresses if now fixed
*p=2;
p=&b; //error
*p=3;
printf("%d %d",a,b);
}
Example 2
main()
{
int a=5,b=6;
int const * p=&a;
//*p=2;
p=&b;
*p=3;
printf("%d %d",a,b);
}
Comments
Post a Comment