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.
More easy Embedded Systems Engineer questions
- What is the difference between a microcontroller and a microprocessor?
- What is an interrupt, and how is it different from polling?
- Compare UART, SPI and I2C. When would you use each?
- When would you use bare-metal firmware versus an RTOS?
- What GPIO modes does a typical microcontroller pin support, and when would you use each?
- What is PWM, how is it generated on a microcontroller, and what is it used for?
- What is a bootloader in an embedded device, and why would a product need one?
- What is endianness, and how do you deal with it when exchanging data between devices?
- How do you approach reading a datasheet for a new sensor or microcontroller?