C Programming · Interview question

What does volatile do, and when must you use it?

A strong answer

volatile tells the compiler that a variable's value can change outside the normal flow of the program, so it must perform every read and write to the actual memory location exactly as written, no caching the value in a register, no eliding "redundant" reads, no reordering relative to other volatile accesses. Two situations make it mandatory. First, memory-mapped hardware registers: the hardware updates a status register independently of your code, so a polling loop without volatile reads it once, caches it, and spins forever on the stale value. Second, variables shared between an ISR and the main flow: the optimizer can't see that the interrupt modifies the flag, so it may hoist the read out of a loop; volatile forces a re-read each iteration. Without it you get bugs that appear only at higher optimization levels, works in debug, breaks in release.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

const, volatile & static

Three small keywords with outsized consequences: const for intent, volatile for hardware and ISR-shared data, static for lifetime and linkage, and why volatile is not atomic.

More const, volatile & static questions

Browse all 472 interview questions