Sample C code that shows instability during disassembly?

What is a short illustrative C program that demonstrates the difference between volatile and nonvolatile when disassembling?

t

int main() { volatile int x; ??? } 

against

 int main() { int x; ??? } 

What can we replace like ??? so that the generated code is different?

+5
source share
3 answers

eg:

 x = 0; 

If x not volatile , the compiler will see that it is not in use and will probably exclude it (either the operator x = 0; or even the variable itself) completely from the generated code as an optimization.

However, the volatile keyword precisely prevents compiler execution. It basically tells the code generator: "Do you think this variable is / does not, donโ€™t think, I need it." Thus, the compiler will treat the volatile variable as accessible, and it will issue the actual code that matches the expression.

+7
source

This may not be the shortest example, but this is the usual use of volatile in embedded systems, if x points to the register address, if volatile not used, the compiler will take the value from x does not change and removes the loop:

 volatile long *x = (long*) REGISTER_BASE; while (!(x&0x01)) { //do nothing; } 
+2
source

You can also try the following:

 x=1; x=2; return x; 

Turn on optimization, check disassembly for both.

0
source

All Articles