Why do you mark a variable shared between an interrupt service routine and your main loop as volatile, and what does volatile NOT protect you from?

technical-conceptual · Junior level · software-engineering

What the interviewer is really asking

Checks whether the candidate understands what volatile actually guarantees (no compiler caching of reads/writes) versus what it does not (atomicity), and that they know to also protect multi-byte access.

What to say

What to avoid

Example answers

Strong: volatile tells the compiler the value can change behind its back, so it can't keep a stale copy in a register across loop iterations. But it doesn't make access atomic. If my ISR updates a 32-bit tick counter and my main loop reads it, on a smaller core that read takes several instructions, so an interrupt could land mid-read and give me a torn value. I'd disable interrupts briefly while I copy the counter out, then re-enable, to make that read atomic.

Weak: You add volatile so the variable is safe to share between the interrupt and the main code. It basically locks it so they don't conflict, and then you don't have to worry about race conditions.

Want questions matched to your role? Paste a job title, job description, or CV and get a personalized set, or go Pro to unlock the full bank.