Volatile Keyword in C/C++

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:

  1. Code that works fine-until you turn optimization on
  2. Code that works fine-as long as interrupts are disabled
  3. Faulty hardware drivers
  4. 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

  1. Memory mapped peripheral register
  2. Global variables modified by an interrupt service routine
  3. 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.