5

I am reading a book on C. It mentions a concept which does not make sense to me. What I know is that the compiler sometimes optimises code by removing variables which it feels would not affect an expression. So if we specify volatile to a variable, it does not remove this variable from any expression.

So the book introduces something like this:

volatile const int a = 1;

The explaination is only a couple of lines, none of which makes sense to me. Can somebody please explain why would be there a need of such a variable?

PS: I understand the concept of volatile, what I dont understand is the concept of volatile const.

Cool_Coder
  • 4,888
  • 16
  • 57
  • 99

2 Answers2

5

A volatile const variable is one whose value may change due to external influences, and which cannot be written to.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
  • thanks for understanding my question in the first place. But if the value of a variable is changing then how can it be const? – Cool_Coder Dec 03 '13 at 14:21
  • 3
    `const` means you cannot write to it. That doesn't mean the value can never change; the variable may map to a hardware register which reads values from a sensor, or something. This is where the `volatile` comes in. – Graham Borland Dec 03 '13 at 14:22
  • 3
    Moreover, it may be changed with const-cast, or by another function/thread where it isn't declared `const` (quite common approach). – keltar Dec 03 '13 at 14:46
  • 1
    @keltar: The C standard does not define the behavior if an attempt is made to modify an object **defined** as const. If code has a pointer to a const type but the pointer is pointing to an object that was not originally defined as const, then it is permitted to convert the pointer to a pointer to non-const and to modify the object via the new pointer. – Eric Postpischil Dec 03 '13 at 15:23
  • @EricPostpischil i was talking more about extern. But yes, that thing too. – keltar Dec 03 '13 at 15:28
1

Volatile const means value cannot be changed programmatically but value can be changed indirectly, for eg if the variable is mapped to device register, then value can be modified by the device.

rajeshsam
  • 169
  • 1
  • 6