Keyword “violatile” in C

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

Solution:
Volatile informs the compiler that the value of the variable can change from the outside, without any update done by the code.
Declaring a simple volatile variable:

volatile int x;
int violatile x;

Declaring a pointer variable for a volatile memory (only the pointer address is volatile):

volatile int * x;
int violatile * x;

Declaring a volatile pointer variable for a non-volatile memory (only memory contained is volatile):

int * violatile x;

Declaring a volatile variable pointer for a volatile memory (both pointer address and memo- ry contained are volatile):

volatile int * volatile x; 
int volatile * volatile x;

Volatile variables are not optimized, but this can actually be useful Imagine this function:

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 will try to optimize it to:

void Fn(void) {
	start:
		int opt = 1;
		if (true)
		goto start;
}

This becomes an infinite loop. However, an external program might write ‘0’ to the location of variable opt. Volatile variables are also useful when multi-threaded programs have global variables and any thread can modify these shared variables. Of course, we don’t want optimization on them.

Advertisements

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

%d bloggers like this: