clanguage-lawyervolatilenon-volatile

Assign volatile to non-volatile sematics and the C standard


volatile int vfoo = 0;
void func()
{
    int bar;
    do
    {
        bar = vfoo;  // L.7
    }while(bar!=1);
    return;
}

This code busy-waits for the variable to turn to 1. If on first pass vfoo is not set to 1, will I get stuck inside.

This code compiles without warning. What does the standard say about this?


Solution

  • What the standard has to say about this includes:

    5.1.2.3 Program execution

    ¶2 Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression in general includes both value computations and initiation of side effects. Value computation for an lvalue expression includes determining the identity of the designated object.

    ¶4 In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).

    ¶6 The least requirements on a conforming implementation are:

    • Accesses to volatile objects are evaluated strictly according to the rules of the abstract machine.
    • ...

    The takeaway from ¶2 in particular should be that accessing a volatile object is no different from something like calling printf - it can't be elided because it has a side effect. Imagine your program with bar = vfoo; replaced by bar = printf("hello\n");