Topics / C Programming / Q35
Can a variable be both const and volatile? What is the difference between them?
Short answer: Yes. const means this program must not write the object; volatile means something else may change it (or that reading it has side effects), so every access must really happen. Together they describe a read-only hardware register: you cannot write it, but you must re-read it every time.
#define USART_SR (*(const volatile uint32_t *)0x40011000u)
while ((USART_SR & TXE) == 0) { } /* re-read on every iteration; USART_SR = 0 is a compile error */
const vs volatile
const |
volatile |
|
|---|---|---|
| Promise made by | the programmer: "this code will not modify it" | the programmer: "it can change outside the program's control" |
| Effect on the compiler | rejects writes; may place the object in flash (.rodata); may assume the value never changes |
must perform every read/write; cannot cache, merge or remove accesses |
| Typical use | lookup tables, configuration, function parameters that must not be modified | hardware registers, ISR-shared flags, memory written by DMA |
| Combined | const volatile: read-only register, or a variable this module only reads but an ISR or hardware writes |
Other examples of const volatile
- A free-running timer counter that software only reads.
- A shared variable that the main loop only reads and an ISR writes: in the main module it could be declared
extern const volatile uint32_t g_ticks;so the main code cannot write it by accident. - A configuration word in flash that the bootloader or a debugger might rewrite.
Order of qualifiers: const volatile uint32_t, volatile const uint32_t and uint32_t const volatile are all the same.