Skip to content
RED SAGSkills
easyEmbedded Systems Engineer interview question

Explain volatile and const in embedded C. Can a variable be both?

What the interviewer wants to hear

  • volatile: value can change outside program control, compiler must not optimise accesses away
  • Used for hardware registers, ISR-shared variables
  • const: program must not modify it; may be placed in flash
  • volatile const for a read-only hardware status register
  • volatile does not guarantee atomicity

Model answer

volatile tells the compiler that a variable can change in ways it cannot see, so every read and write must really happen in memory and not be cached in a register or removed. I use it for memory-mapped hardware registers, variables shared between an ISR and the main loop, and variables changed by DMA. const means my code is not allowed to modify the value, and constant data can be placed in flash instead of RAM, which is important when RAM is small. Yes, a variable can be both: a read-only hardware status register is a good example. My code must not write it, so it is const, but the hardware changes it, so it is volatile. One important point: volatile does not make operations atomic or thread-safe, so a shared counter still needs a critical section or atomic operations.

Can you answer it under time pressure?

Take a timed easy round and get scored on every answer.

Start mock interview

More easy Embedded Systems Engineer questions