Volatile 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 any time. The implications of this are quite serious.
It is required when you experience the following in C/C++ code:
- Code that works fine-until you turn optimization on
- Code that works fine-as long as interrupts are disabled
- Faulty hardware drivers
- Tasks that work fine in isolation-yet crash when another task is enabled
Syntax:
For declaration of volatile variable, make use of volatile keyword before or after the datatype. For instance
int volatile num;
volatile int num;
Pointer can also be declared as volatile:
int volatile *ptr;
volatile int *ptr;
Hence, if you apply volatile to struct or union, the entire contents of the struct/union are volatile. Perhaps, if we don’t want this behavior, the apply the volatile qualifier to the individual members of the struct/union.
When should be volatile used?
A variable should be declared volatile whenever its value could change unexpectedly. For instance
- Memory mapped peripheral register
- Global variables modified by an interrupt service routine
- Global variables within a multi-threaded application
Conclusion
Volatile keyword is used to change the variable whose values can be changed and it doesn’t have any constant value. The volatile qualifier is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. volatile qualifier are mainly used for global variables.