Example C code that demonstrates volatile in disassembly?

China☆狼群 提交于 2019-12-10 13:45:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!