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.
const int temp; is a variable stored in (read-ony)FLASH, initialized to 0 at compiler time, cached values may be used. volatile int temp; is a variable stored in RAM, initialized to 0 at startup (cstart), cached values will NOT be used.
Introduction to Volatile in C. A volatile keyword in C is nothing but a qualifier that is used by the programmer when they declare a variable in source code. It is used to inform the compiler that the variable value can be changed any time without any task given by the source code.
C's volatile keyword is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time--without any action being taken by the code the compiler finds nearby.
Yes a C++ variable be both const and volatile. It is used in situations like a read-only hardware register, or an output of another thread. Volatile means it may be changed by something external to the current thread and Const means that you do not write to it (in that program that is using the const declaration).
A volatile const
variable is one whose value may change due to external influences, and which cannot be written to.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With