In a microcontroller program, a button press sets a flag inside an interrupt service routine (ISR), and the main loop waits for that flag. (a) Why use an interrupt instead of polling the pin? (b) Why must the flag be declared volatile in C?
Show the explanation
Model answer. (a) Polling checks the pin repeatedly, wasting CPU time and power and possibly missing short presses between checks. An interrupt makes the hardware call the ISR as soon as the event happens, so the CPU can sleep or do other work.
(b) The main loop reads the flag but never writes it; without volatile the compiler may assume it cannot change, keep it in a register and turn while (!flag); into an infinite loop. volatile forces a fresh memory read every time. Note that volatile does not make multi-byte updates atomic — for shared multi-byte data, disable interrupts briefly or use atomic types. Keep ISRs short: set a flag, do the work in the main loop.
Original UniCircle question. Last reviewed 21 Oct 2026.
