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.
-
3http://stackoverflow.com/questions/4592762/difference-between-const-const-volatile – shree.pat18 Nov 19 '15 at 02:45
-
1`const` doesn't mean something won't change. – Nov 19 '15 at 02:48
-
You say "By definition however, volatile variables can change at any time even by code outside the current scope." That's not really what volatile means. volatile means that the value must be refreshed (i.e. loaded into a register, examined, etc.) each time it is used in case another piece of code or thread edits that value. This ensure that the most up to date value is used. Thus, it cannot use cached copies of the variable. const means that you can't use c code to change a value. There are tricks like casting out const. However, sometimes your link settings put consts in ROM. – jaybers Nov 19 '15 at 02:57
2 Answers
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/

- 16,808
- 7
- 52
- 98
Yes, it is possible.
The best example is Status Register in controllers, in the program we should not modify this Status Register so it should be a constant. But this can be changed by the processor or hardware based on the interrupt condition. So when in the program, we want to read the value of this Status Register, it should read the actual value with out any optimization. For this reason, the Status Registers can be declared as volatile too. Example:
uint32_t volatile * const Spi_status_reg = (uint32_t *) 0x000800F0;
The best way to read a declaration like this is from the name of the variable back to the left: here Spi_status_reg is a constant pointer to a volatile 32-bit unsigned integer.

- 2,868
- 2
- 25
- 40

- 11
- 2
-
1in your answer the status_register, is volatile uint32, and the pointer to it is const. So this is not an answer to the question, because the variable in your example does not have both const and volatile qualifiers... – fazkan Oct 04 '18 at 05:54