Can a variable be both const and volatile? Give a real example.
0 upvotes
Practice with AISoon
Yes. A const volatile variable is one the program must not write to, but whose value can still change externally. The classic example is a read-only hardware status register: it is const because the software should never write to it (and the compiler will error if you try), and volatile because the hardware updates it asynchronously between reads.
c
const volatile uint32_t * const STATUS = (const volatile uint32_t *)0x40021000;// Read-only from software, changes every time hardware updates itwhile (!(*STATUS & READY_BIT)) { /* poll */ }
This is one of the most commonly asked C interview questions. Candidates who say "const and volatile are contradictory" reveal a misunderstanding of what const means in C — it means "read-only from this code's perspective," not "the value never changes."
Source: C / C++ Concepts Q&A
