What is the use of volatile keyword in C/C++? What is the difference between declaring a variable volatile and not declaring it as volatile?
Volatile tells to compiler that this value might change and the compiler should not do any optimization on it. An example of it.
/** port to read temperature **/
#define PORTBASE 0x40000000
unsigned int volatile * const port = (unsigned int *) PORTBASE;
for(;;)
{
if(*port == 300)
{
/** shutdown the system **/
}
}
If port is not volatile, then the compiler will assume that the value cannot be changed. It will never do the checking if *port == 300. However, the value can be changed based on the sensor. We put volatile to tell compiler that don't do any optimization on it. Thumb rule is when using the memory mapped registers, whose value can change based on the circumstance, then use volatile keyword.