Constant Pointer vs Pointer to Constant C Program

In previous post we discussed about pointers, how to define and use pointers. In this post we will learn what’s the difference between constant pointer and pointer to constant.

If we define a pointer as constant then we cannot modify its memory address. For example if we assigned the memory address of a variable ‘a’ to the pointer ‘ptr’. Now if we try to assign the address of the variable ‘b’ to the pointer ‘ptr’ then compiler will throw an error message. This means that we cannot change/modify the address assigned to the constant pointer but we can modify/change the value to which that pointer is pointing.

In contrast, if we define a pointer to constant value, then we can modify/change the address assigned to the pointer. But we cannot modify/change the value to which the pointer is pointing. Following simple program will clarify the difference between a constant pointer and a pointer to constant.


#include <stdio.h>
void constPtr(int * const ptr);
void ptrToConst(const int * ptr);
int main(void){

   int count = 5;

   constPtr(&count); //here we passed address of the count variable to the function which is accepting it as a constant pointer
   ptrToConst(&count); //here we passed address of the count variable to the function which is accepting it as a pointer to constant

   return 0;
}

void constPtr(int * const ptr){
   int j= 10;

   //ptr = &j; // will generate an error because we cannot assign new address to constant pointenr

   printf("Old value to which pointer is pointing: %d\n", *ptr);

   *ptr = *ptr * 2; //this is valid becuase in constant pointer we can modify/change the value to which that pointer is pointing

   printf("New value to which pointer is pointing: %d\n", *ptr);
}

void ptrToConst(const int * ptr){
   int i = 12;

   ptr = &i; // this is valid because we can change/modify the address assigned to a pointer to constant

   //*ptr = *ptr * 2; // will generate an error because we cannot modify/change the value to which that pointer is pointing

   printf("Value to which pointer is pointing now: %d\n", *ptr);

}

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *