What is a short illustrative C program that demonstrates the difference between volatile and non-volatile in the disassembly?
ie
int main()
{
volatile int x;
???
}
vs
int main()
{
int x;
???
}
What can we replace both ??? with such that the generated code is different?
for example:
If
xis notvolatile, the compiler will see that it’s unused and will probably eliminate it (either thex = 0;statement or even the variable itself) completely from the generated code as an optimization.However, the
volatilekeyword is exactly for preventing the compiler from doing this. It basically tells the code generator “whatever you think this variable is/does, don’t second guess me, I need it.” So then the compiler will treat the volatile variable as accessed and it will emit the actual code corresponding to the expression.