简体   繁体   中英

Example C code that demonstrates volatile in disassembly?

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:

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.

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;
}

You can also try this:

x=1;
x=2;
return x;

Turn on optimization an check the disassembly for both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM