Write about Constant Pointers in C


Constant Pointers
A constant pointer is a pointer that cannot change the address its holding. In other words, we can say that once a constant pointer points to a variable then it cannot point to any other variable.
A constant pointer is declared as follows :
< type of pointer >  *  const < name of pointer >
An example declaration would look like :
int * const ptr;
Lets take a small code to illustrate these type of pointers :
#include

int main(void)
{
    int var1 = 0, var2 = 0;
    int *const ptr = &var1;
    ptr = &var2;
    printf("%d\n", *ptr);

    return 0;
}
In the above example :
  • We declared two variables var1 and var2
  • A constant pointer ‘ptr’ was declared and made to point var1
  • Next, ptr is made to point var2.
  • Finally, we try to print the value ptr is pointing to.
So, in a nutshell, we assigned an address to a constant pointer and then tried to change the address by assigning the address of some other variable to the same constant pointer.

Related

C Language 8319154077658130346

Post a Comment

emo-but-icon

item