tags:

views:

132

answers:

3

Possible Duplicate:
What is the difference between these declarations in C?

what is purpose of volatile?

A: 

Google is your friend:

How To Use C's volatile Keyword

Using the volatile keyword in C

Onorio Catenacci
A: 

Volatile basically tells the compiler not to perform any optimizations on the "object" that you're applying it to.

This is useful when the object can be changed outside the scope of the program.

One example (and there are others) is with embedded systems. Let's say you have a device with a memory mapped keyboard. Whenever the user presses a key, the ASCII code for that key shows up in memory location 0xff00 (for example).

So you start with the code:

char *kbdata = 0xff00;

then, whenever you want to wait for a key to be pressed, you can poll:

char key = *kbdata;
while (key == 0)
    key = *kbdata;

The only problem here is that the compiler may figure out that nothing in the code is changing *kbdata so it may optimize the accesses so that the code no longer works. Most likely it will load *kbdata into key once then enter an infinite loop.

By specifying kbdata as volatile, the compiler will make sure it doesn't try to optimize accesses to it and the code should work as expected.

paxdiablo