Volatile (computer programming)

This is an old revision of this page, as edited by 128.54.63.194 (talk) at 00:10, 26 January 2007 (What can happen if volatile is not used?: Mention possibility of another thread and shared memory; expand a sentence). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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.

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 so it will remain equal to 0. 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 (computer science) or process (computing) 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;
    addr = 100;
    
    *addr = 0;

    while (*addr != 255)
        ;
}

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