Friday, February 12, 2010

Introduction to ' volatile ' keyword of C

Many people doesn't know much about volatile keyword of ANSI C. All C programmers wont use this keyword. Low level Embedded software developers, firmware developers use this keyword to play with hardware.

I got some important points on volatile keyword and i am sharing the same information with you. This will make me to get familiarized with volatile keyword.

Volatile keyword:

volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any fraction of time.

To declare a variable volatile, include the keyword volatile before or after the data type in the variable definition.

    volatile int foo;
    int volatile foo;


Now, it turns out that pointers to volatile variables are very common. Both of these declarations declare foo to be a pointer to a volatile integer:

    volatile int * foo;
    int volatile * foo;


Volatile pointers to non-volatile variables are very rare.

     int * volatile foo;

And just for completeness, if you really must have a volatile pointer to a volatile variable, then:

     int volatile * volatile foo;

Use of Volatile Keyword

A variable should be declared volatile whenever its value could change unexpectedly. In practice, only three types of variables could change:

• Memory-mapped peripheral registers
• Global variables modified by an interrupt service routine
• Global variables within a multi-threaded application

As a middleware developer or embedded software developer, i have used volatile keyword for a global variable which was shared between multiple threads (WinCE threads). Without volatile also, it was working. But for better practice, i have used once.

I think some Real-time operating systems make all variables volatile by default except constants.

I think this much is enough to know about Volatile keyword.

Good luccccccccccccck.........