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?
vfoois declared asvolatile. Therefore, read to this variable should not be optimized.- However, bar is not
volatilequalified. Is the compiler allowed to optimize the write to thisbar? .i.e. the compiler would do a read access tovfoo, and is allowed to discard this value and not assign it tobar(at L.7). - If this is a special case where the standard has something to say, can you please include the clause and interpret the standard's lawyer talk?
What the standard has to say about this includes:
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 withbar = vfoo;replaced bybar = printf("hello\n");