Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why volatile vars are 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, the disassembly looks like:

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 any side effect from it? it's the only code in the program, so why the optimizer can't just throw it off?

like image 755
Alek86 Avatar asked Nov 23 '11 21:11

Alek86


1 Answers

From this reference page:

volatile - the object can be modified by means not detectable by the compiler and thus some compiler optimizations must be disabled.

like image 120
Some programmer dude Avatar answered Nov 15 '22 05:11

Some programmer dude