Const Pointers

suggest change

Single Pointers

The pointer can point to different integers, and the int can be changed through the pointer. This sample points p at b, then stores 100 through p.

int b;
int* p;
p = &b;    /* OK */
*p = 100;  /* OK */

The pointer can point to different integers, but the int's value cannot be changed through the pointer.

int b;
const int *p;
p = &b;    /* OK */
*p = 100;  /* Compiler error */

The pointer can only point to one int but the int’s value can be changed through the pointer.

int a, b;
int* const p = &b; /* OK as initialisation, no assignment */
*p = 100;  /* OK */
p = &a;    /* Compiler Error */

The pointer can point to only one int, and that int cannot be changed through the pointer.

int a, b;
const int* const p = &b; /* OK as initialisation, no assignment */
p = &a;   /* Compiler Error */
*p = 100; /* Compiler Error */

Pointer to Pointer

This code stores the address of p1 in the pointer to pointer p. It then points p1 at a and stores 100 in a.

void f1(void)
  {
    int a, b;
    int *p1;
    int **p;
    p1 = &b; /* OK */
    p = &p1; /* OK */
    *p = &a; /* OK */
    **p = 100; /* OK */
  }
void f2(void)
{
 int b;
 const int *p1;
 const int **p;
 p = &p1; /* OK */
 *p = &b; /* OK */
 **p = 100; /* error: assignment of read-only location ‘**p’ */
}
void f3(void)
{
  int b;
  int *p1;
  int * const *p;
  p = &p1; /* OK */
  *p = &b; /* error: assignment of read-only location ‘*p’ */
  **p = 100; /* OK */
}
void f4(void)
{
  int b;
  int *p1;
  int ** const p = &p1; /* OK as initialisation, not assignment */
  p = &p1; /* error: assignment of read-only variable ‘p’ */
  *p = &b; /* OK */
  **p = 100; /* OK */
}
void f5(void)
{
  int b;
  const int *p1;
  const int * const *p;
  p = &p1; /* OK */
  *p = &b; /* error: assignment of read-only location ‘*p’ */
  **p = 100; /* error: assignment of read-only location ‘**p’ */
}
void f6(void)
{
  int b;
  const int *p1;
  const int ** const p = &p1; /* OK as initialisation, not assignment */
  p = &p1; /* error: assignment of read-only variable ‘p’ */
  *p = &b; /* OK */
  **p = 100; /* error: assignment of read-only location ‘**p’ */
}
void f7(void)
{
  int b;
  int *p1;
  int * const * const p = &p1; /* OK as initialisation, not assignment */
  p = &p1; /* error: assignment of read-only variable ‘p’  */
  *p = &b; /* error: assignment of read-only location ‘*p’ */
  **p = 100; /* OK */
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents