Consider this code example:
int main(void)
{
volatile int a;
static volatile int b;
volatile int c;
c = 20;
static volatile int d;
d = 30;
volatile int e = 40;
static volatile int f = 50;
return 0;
}
Without volatile
a compiler could optimize away all the variables since they are never read from.
I think a
and b
can be optimized away since they are completely unused, see unused volatile variable.
I think c
and d
can not be removed since they are written to, and writes to volatile variables must actually happen. e
should be equivalent to c
.
GCC does not optimize away f
, but it also does not emit any instruction to write to it. 50 is set in a data section. LLVM (clang) removes f
completely.
Are these statements true?
- A volatile variable can be optimized away if it is never accessed.
- Initialization of a static or global variable does not count as access.