0

I'm fairly new to C. Can someone explain to me the difference between the following? In terms of both usage and concept.

int *const p= &x;

int const *p= &x; 

const int *const p= &x;

or any other variation of pointer usage that would help me understand the concept fully.

dbush
  • 205,898
  • 23
  • 218
  • 273

1 Answers1

0

The constness applies to 1) the pointer itself - whether it can change to point to something else after initialisation, and 2) the data the pointer points to - whether the data can change or not via the pointer.

int *const p= &x;   // p is const pointer to non-const data - p cannot change to point to something else, but you can change what it points to

int const *p= &x;   // p is non-const pointer to const data - p can change to point to something else, but what it points to cannot be changed

const int *const p= &x; // p is const pointer to const data - p cannot change to point to something else, and what it points to cannot be changed
artm
  • 17,291
  • 6
  • 38
  • 54