w3resource

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

C - const int*, const int * const, and int const *?

  • int* ptr1 – ptr1 is a pointer to int
  • int const * ptr2 - ptr2 is a pointer to const int
  • int * const ptr3 - ptr3 is a const pointer to int
  • int const * const ptr4 - ptr4 is a const pointer to const int
    Now the first const can be on either side of the type so:
  • const int * ptr1 == int const * ptr1
  • const int * const ptr2 == int const * const ptr2
    You can do things like this:
  • int ** ptr1 - ptr1 is a pointer to pointer to int
  • int ** const ptr2 - ptr2 is a const pointer to a pointer to an int
  • int * const * ptr3 - ptr3 is a pointer to a const pointer to an int
  • int const ** ptr4 - ptr4 is a pointer to a pointer to a const int
  • int * const * const ptr5 - ptr5 is a const pointer to a const pointer to an int

Example: Pointer to Constant

#include <stdio.h>
int main() 
{
  const int x = 10;
  const int y = 20;
  const int *z = &x; /* z is a "pointer to a constant." */
  x = 30; /* Error. Cannot change x. */
  y = 40; /* Error. Cannot change y. */
  z = &y; /* OK. */
 *z = 50; /* Error. Cannot change *z */
  return 0;
}

Example: Constant Pointer:

#include <stdio.h>
int main() {
int x = 10;
int y = 20;
int *const z = &x; /* z is a "constant pointer." */
x = 30; /* OK. */
y = 40; /* OK. */
z = &y; /* Error. Cannot change z. */
*z = 500; /* OK. */ 
return 0;
}

Example: Constant Pointer to Constant

#include <stdio.h>
int main() 
{
  const int x = 10;
  const int y = 20;
  const int *const z = &x; /* z is a "constant pointer to a constant." */
  x = 30; /* Error. Cannot change x. */
  y = 40; /* Error. Cannot change y. */
  z = &iSecond; /* Error. Cannot change z. */
 *z = 50; /* Error. Cannot change *z. */ 
  return 0;
}


Follow us on Facebook and Twitter for latest update.