What does const int *p, int *const p and const int *const p mean?
Short answer: Read the declaration from the variable name outward (right to left). const int *p is a pointer to a constant int: you can move p, but not change *p. int *const p is a constant pointer to int: you can change *p, but p always points to the same place. const int *const p allows neither.
| Declaration | Can change p? |
Can change *p? |
Read as |
|---|---|---|---|
const int *p / int const *p |
yes | no | p is a pointer to const int |
int *const p = &x; |
no | yes | p is a const pointer to int |
const int *const p = &x; |
no | no | p is a const pointer to const int |
int x = 1, y = 2;
const int *a = &x; a = &y; /* OK */ /* *a = 5; error */
int *const b = &x; *b = 5; /* OK */ /* b = &y; error */
const int *const c = &x; /* neither */
Where const is placed relative to * is what matters: const before the * applies to the pointed-to data; after the * applies to the pointer itself.
Embedded examples
/* fixed address, changing contents: const pointer to volatile data */
volatile uint32_t *const UART_DR = (volatile uint32_t *)0x40011004u;
/* function promises not to modify the caller's buffer */
size_t crc16(const uint8_t *data, size_t len);
/* table of strings, all in flash: const pointers to const chars */
static const char *const state_names[] = { "IDLE", "RUN", "ERROR" };
In the last example, without the second const, the array of pointers is writable and so goes into RAM (.data), even though the strings are in flash.
Follow-up: "Can you remove const with a cast?" You can cast const int * to int *, but writing through it is undefined behaviour if the object was originally defined const (it may be in flash, where the write is ignored or faults).