Difference between const int*, const int * const, and int const * in C


Pointer

In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer.

const int* and int const* says that the pointer can point to a constant int and value of int pointed by this pointer cannot be changed. But we can change the value of pointer as it is not constant and it can point to another constant int.

const int* const says that the pointer can point to a constant int and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant int.

Thumb rule is to naming syntax from right to left.

// constant pointer to constant int
const int * const
// pointer to constant int
const int *

Example (C)

Uncomment the commented erroneous codes and see the error.

 Live Demo

#include <stdio.h>
int main() {
   //Example: int const*
   //Note: int const* is same as const int*
   const int p = 5;
   // q is a pointer to const int
   int const* q = &p;
   //Invalid asssignment
   // value of p cannot be changed
   // error: assignment of read-only location '*q'
   //*q = 7;
   const int r = 7;
   //q can point to another const int
   q = &r;
   printf("%d", *q);
   //Example: int const* const
   int const* const s = &p;
   // Invalid asssignment
   // value of s cannot be changed
   // error: assignment of read-only location '*s'
   // *s = 7;
   // Invalid asssignment
   // s cannot be changed
   // error: assignment of read-only variable 's'
   // s = &r;
   return 0;
}

Output

7

Updated on: 06-Jan-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements