Can a pointer be volatile? Explain the declarations.
Short answer: Yes; the position of volatile relative to * decides what is volatile, exactly like const. volatile int *p is a pointer to volatile data (the normal case for registers). int *volatile p is a volatile pointer to normal data (the pointer variable itself may be changed by an ISR). volatile int *volatile p makes both volatile.
| Declaration | What is volatile | Typical use |
|---|---|---|
volatile uint32_t *p |
the data *p |
pointer to a hardware register or a DMA buffer |
uint32_t *volatile p |
the pointer p |
a buffer pointer that an ISR swaps (double buffering) |
volatile uint32_t *volatile p |
both | an ISR-swapped pointer to a buffer that DMA writes |
volatile uint32_t *const p |
the data; the pointer is constant | fixed register address |
const volatile uint32_t *p |
data is volatile and read-only through p |
read-only status register |
/* fixed register: the address never changes, the contents do */
volatile uint32_t *const UART_DR = (volatile uint32_t *)0x40004404u;
/* double buffering: the ISR flips which buffer the main loop processes */
static uint8_t buf_a[64], buf_b[64];
static uint8_t *volatile ready_buf; /* pointer written by the ISR */
void DMA_IRQHandler(void) { ready_buf = (ready_buf == buf_a) ? buf_b : buf_a; }
Reading tip: read right to left from the name. int *volatile p: "p is a volatile pointer to int". volatile int *p: "p is a pointer to an int that is volatile".
Pointers to volatile structs: declaring the struct members volatile (as CMSIS does: __IO uint32_t CR;) or the pointer target volatile GPIO_TypeDef * both make every member access volatile.
Casting away volatile ((uint32_t *)p from volatile uint32_t *) and then accessing the object is undefined behaviour if the object was defined volatile, and in practice lets the compiler optimise away accesses you need.