Generally C text does not give specific importance to Volatile specifier and dismiss this important topic with minimal description. But today I am thinking into diving little bit deeper into this topic to give it its deserving value. So lets start with the generic statement about volatile qualifier which everyone is familiar with.
A volatile qualifier is added to variable declaration in C when the value of that variable is expected to change unexpectedly(i.e. across its different access by different components). The implication of volatile keyword on compiler is that it will not optimize this variable for subsequent read and writes.
So what exactly is the optimization performed by compiler in terms of variables used inside the code? In a very naive explanation, I can say at basic level of optimization, compiler used to cache the values of variables so that memory I/O operations can be avoided at every variable read access. But in certain scenarios such optimization is not desirable.
Few of these scenarios that I can recall currently are listed below :
- Multi- threaded applications
- Code which uses Interrupts
- Hardware drivers
So for the above listed scenarios, if the variables are optimized the code keeps on using its cached value while that specific variable may be modified by some other task or interrupt which may lead to ambiguous results and hard to debug as well. So using volatile type qualifier in your code can save the programmer to avoid such errors. Now we will talk about its usage (when and how to use it.)
Syntax of using volatile qualifier in C is :
volatile int var; /* Volatile variable declaration. */
int volatile var; /* Alternate format for declaring volatile variable. */
So when to use it :
- for memory mapped registers in hardware peripheral devices.
- for global variables which are being shared among multiple tasks in multi-threaded environment.
- for global variables which can be modified and used by Interrupt Service Routines.
Word of Caution :
If volatile is applied to structure or union in C, then their entire contents gets volatile, if this is not the requirement its better to apply volatile keyword on specific variables in structures and unions.
End Note :
So in the next part on volatile variables we will see how to use them in different scenarios using code examples. Till then keep exploring !!! See you soon guys 🙂