Alek86
Alek86

Reputation: 1569

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?

Upvotes: 5

Views: 280

Answers (5)

Rob K
Rob K

Reputation: 8926

If i is mapped to a register on an add-in board, it would be very bad for the compiler to make assumptions about the content of it.

i = 1;
i = 2;

This could be issuing commands to a piece of hardware. Skipping command '1' could give some pretty bad results.

Upvotes: 2

FailedDev
FailedDev

Reputation: 26940

Well because volatile tells the compiler that the variable can be accessed/changed in ways that cannot be seen by the compiler. Typically used in embedded software where a hardware interrupt for example can change the value of a variable.

Upvotes: 5

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

If volatile vars could be optimized away, that would kind of defeat their purpose, wouldn't it? Putting volatile on a var is telling the compiler that you know something it doesn't. Something could be happening to this var completely outside the scope of the program. If the compiler optimized that away, it would spoil those plans.

Upvotes: 8

Some programmer dude
Some programmer dude

Reputation: 409442

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.

Upvotes: 11

K-ballo
K-ballo

Reputation: 81399

The volatile modifier means that the variable is likely to change or be read outside of the control of the program under compilation. There is nothing to be optimized.

Upvotes: 4

Related Questions