volatile and const in Embedded C
volatile tells the compiler a value can change outside the program's control; const promises it won't be modified.
Intermediate
volatile is essential for:
- hardware registers (
*(volatile uint32_t *)0x40020014), - variables shared with an interrupt service routine,
- variables changed by another thread or DMA.
volatile bool data_ready = false; // set inside an ISR
ISR(USART_RX_vect) { data_ready = true; }
while (!data_ready) { } // without volatile this could loop forever
const marks read-only data; on microcontrollers const tables are often placed in flash instead of RAM. A register can even be const volatile (read-only, but changes on its own).
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.