Why are unstable vars not optimized even in very simple cases?

if i compile the code

int main()
{
    int i;
    i = 1;
    i = 2;
}

in VS with Release and optimization, disassembly looks like this:

int main()
{
    int i;
    i = 1;
    i = 2;
}
010D1000  xor         eax,eax 
010D1002  ret

but if I write the word "volatile":

int main()
{
01261000  push        ecx  
    volatile int i;
    i = 1;
01261001  mov         dword ptr [esp],1 
    i = 2;
01261008  mov         dword ptr [esp],2 
}
0126100F  xor         eax,eax 
01261011  pop         ecx  
01261012  ret   

Does anyone know why VS leaves this code? is there a side effect of it? this is the only code in the program, so why can't the optimizer just throw it away?

+5
source share
5 answers

From this man page:

volatile - an object can be modified using tools that cannot be detected by the compiler, and therefore some compiler optimizations should be disabled.

+11
source

, , ? volatile var , -, . - var . , .

+8

, volatile , / , . , , , .

+5

volatile , , , . .

+4

If it imatches the case on the board, it would be very bad if the compiler made assumptions about its contents.

i = 1;
i = 2;

This may be the issue of commands for a piece of equipment. Skipping the “1” command can give pretty good results.

+2
source

All Articles