Search code examples
cconstantsvolatile

Can an integer variable have both const and volatile qualifier in C?


I would like to know if this is possible and where something like this can be applied. I got asked this question somewhere and my thinking is you would have a const for something whose value you know is not going to change or rather you would not want to change. By definition however, volatile variables can change at any time even by code outside the current scope. So it seems to me that both these two qualifiers contradict each other.


Solution

  • Yes, there are cases where it can make sense. In summary, a const volatile means that the code cannot change the value of the variable, but something outside of the program can. Some usecases for this include:

    • Read-only hardware registers

    • Read-only shared memory buffers where one CPU writes and another only reads

    Here is a good article with much more detail: http://embeddedgurus.com/barr-code/2012/01/combining-cs-volatile-and-const-keywords/