问题
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?
回答1:
for example:
x = 0;
If x is not volatile, the compiler will see that it's unused and will probably eliminate it (either the x = 0; statement or even the variable itself) completely from the generated code as an optimization.
However, the volatile keyword 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.
回答2:
This may not be the shortest example, but it's a common use of volatile in embedded systems, assuming x points to the address of a register, if volatile is not used, the compiler will assume the value of x doesn't change and will remove the loop:
volatile long *x = (long*) REGISTER_BASE;
while (!(x&0x01)) {
//do nothing;
}
回答3:
You can also try this:
x=1;
x=2;
return x;
Turn on optimization an check the disassembly for both.
来源:https://stackoverflow.com/questions/13207077/example-c-code-that-demonstrates-volatile-in-disassembly