Volatile

What is the significance of the keyword “volatile” in C?

The keyword volatile informs the compiler that the value of variable it is applied to can change from the outside, without any update done by the code. This may be done by the operation system, the hardware, or another thread. Because the value can change unexpectedly, the compiler will therefore reload the value each time from memory.

A volatile integer can be declared by either of the following statements:

C++:
int volatile x;
volatile int x;
To declare a pointer to a volatile integer, we do the following:
C++:
volatile int* x;
int volatile* x;
A volatile pointer to non-volatile data is rare, but can be done.
C++:
int* volatile x;
If you wanted to declare a volatile variable pointer for volatile memory(both pointer address and memory contained are volatile), you would do the following:
C++:
int volatile* volatile x;
Volatile variables are not optimized, which can be very useful. Imagine this function:
C++:
int opt=1;
void Fn(void){
 start:
     if(opt==1) goto start;
     else break;
}

At first glance, our code appears to loop infinitely. The compiler may try to optimize it to:

C++:
void Fn(void){
 start:
     int opt=1;
     if(true)
     goto start;
}
This becomes an infinite loop. However, an external operation might write ‘0’ to the location of variable opt, thus breaking the loop.
To prevent the compiler from performing such optimization, we want to signal that another element of the system could change the variable. We do this using the volatile keyword, as shown below:
C++:
volatile int opt=1;
void Fn(void){
 start:
     if(opt==1) goto start;
     else break;
}
Volatile variables are also useful when multi-threaded programs have global variables and any thread can modify these shared variables. We may not want optimization on these variables.
Advertisements
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s