Volatile variable

From Wikipedia, the free encyclopedia

In computer programming, a variable or object declared with the volatile keyword may be modified externally from the declaring object. For example, a variable that might be concurrently modified by multiple threads should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at any time. Note that operations on a volatile variable are still not atomic. a

[edit] What can happen if volatile is not used?

The following piece of C source code demonstrates the use of the volatile keyword.

void foo(void)
{
    int *addr;
    addr = 100;
    
    *addr = 0;

    while (*addr != 255)
        ;
}

In this example, the code sets the value stored at location 100 in the computer system to 0. It then starts to poll the address until it changes to 255.

An optimizing compiler will assume that no other code will change the value stored in location 100 and assume that it will remain equal to 0 at all times. The compiler will then replace the while loop with something similar to this: -

 
void foo(void)
{
    int *addr;
    addr = 100;
    
    *addr = 0;

    while (TRUE)
        ;                      /* do nothing, just loop */
}

and the program will loop forever.

However, the address might represent a location that can be changed by other elements of the computer system. For example, it could be a hardware register of a device connected to the CPU. The value stored there could change at any time. Or, the variable may be modified by another thread or process via shared memory. The above code would never detect such a change; without the volatile keyword, the compiler assumes the current program is the only part of the system that could cause the value to change. (This is by far the most common situation)

To prevent the compiler from modifying code in this way, the volatile keyword is used in the following manner:

void foo(void)
{
    volatile int *addr;

   /*...same as before */
}

With this modification the code will remain as it is and the CPU will detect the change when it occurs.

[edit] External links