Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't compiler optimize these 2 statements out?

Is there any reason that the compiler cannot optimize the following 2 statements out in main even I turned on fully optimization in Visual C++? Any side effect to access a int variable in memory?

int _tmain(int argc, _TCHAR* argv[])
{
    volatile int pleaseOptimizeMeOut = 100;

    (pleaseOptimizeMeOut);

    return 0;
}
like image 796
Thomson Avatar asked Sep 27 '10 03:09

Thomson


People also ask

How does the compiler optimize?

Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.

Why would the C++ compiler try to optimize out function calls for the code that makes them up?

Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program. The compiler performs optimization based on the knowledge it has of the program.

How do I keep my compiler from optimizing variables?

Select the compiler. Under the Optimization category change optimization to Zero. When done debugging you can uncheck Override Build Options for the file. In the latter case the volatile defined inside the function can get optimized out quite often. ...

Why is compiler optimization important?

Optimizing compilers are a mainstay of modern software: allowing a programmer to write code in a language that makes sense to them, while transforming it into a form that makes sense for the underlying hardware to run efficiently.


1 Answers

It can't optimise them out because you have declared the variable to be volatile. Loads and stores to volatile qualified objects are part of the "externally visible" effects of the C abstract machine.

(By the way, there are plenty of side effects when accessing a variable in memory; it can update hardware memory caches including the TLB, and possibly also cause page faults. And the memory your process is executing in might be being snooped on by another process, like a debugger).

like image 90
caf Avatar answered Sep 27 '22 22:09

caf