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?
vfoo
is declared as volatile
. Therefore, read to this variable should not be optimized.volatile
qualified. Is the compiler allowed to optimize the write to this bar
? .i.e. the compiler would do a read access to vfoo
, and is allowed to discard this value and not assign it to bar
(at L.7).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");
volatile variable has to be read on any access. In your code snippet that read cannot be optimized out. The compiler knows that bar
might be affected by the side effect. So the condition will be checked correctly.
https://godbolt.org/z/nFd9BB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With