What do you mean by pointer to a constant in C language?

CServer Side ProgrammingProgramming

The value of the pointer address is constant that means we cannot change the value of the address that is pointed by the pointer.

A constant pointer is declared as follows −

Data_Type const* Pointer_Name;

For example, int const *p// pointer to const integer

Example

Following is the C program to illustrate a pointer to a constant −

#include<stdio.h>
int main(void){
   int var1 = 100;
   // pointer to constant integer
   const int* ptr = &var1;
   //try to modify the value of pointed address
   *ptr = 10;
   printf("%d\n", *ptr);
   return 0;
}

Output

When the above program is executed, it produces the following result −

Display error, trying to change the value of pointer to constant integer

Example

Following C program demonstrates what happens if we remove const −

 Live Demo

#include<stdio.h>
int main(void){
   int var1 = 100;
   // removed the pointer to constant integer
   int* ptr = &var1;
   //try to modify the value of pointed address
   *ptr = 10;
   printf("%d\n", *ptr);
   return 0;
}

Output

When the above program is executed, it produces the following result −

10
raja
Published on 08-Mar-2021 07:00:06
Advertisements