Volatile keyword

A volatile keyword is a qualifier that prevents the objects, from compiler optimization and tells the compiler that the value of the object can change at any time without any action being taken by the code.

It prevents the cache from a variable into a register and ensures that every access variable is fetched from the memory.

According to C standard, an object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects.

The volatile keyword is mainly used where we directly deal with GPIO, interrupt, or flag Register. It is also used where a global variable or buffer is shared between the threads.

Declaration of volatile in C:

Like const, volatile is also a qualifier. So we only need to put the volatile keyword after or before the data type for the volatile variable at the time of variable declaration.

// Behavior of both variables should be same

int volatile data1;

volatile int data2;

Posted on by