I'm reviewing a C++ MFC project. At the beginning of some of the files there is this line:
#pragma optimize("", off)
I get that this turns optimization off for all following functions. But what would the motivation typically be for doing so?
I'm reviewing a C++ MFC project. At the beginning of some of the files there is this line:
#pragma optimize("", off)
I get that this turns optimization off for all following functions. But what would the motivation typically be for doing so?
I've seen production code which is correct but so complicated that it confuses the optimiser into producing incorrect output. This could be the reason to turn optimisations off.
However, I'd consider it much more likely that the code is simply buggy, having Undefined Behaviour. The optimiser exposes that and leads to incorrect runtime behaviour or crashes. Without optimisations, the code happens to "work." And rather than find and remove the underlying problem, someone "fixed" it by disabling optimisations and leaving it at that.
Of course, this is about as fragile and workarounds can get. New hardware, new OS patch, new compiler patch, any of these can break such a "fix."
Even if the pragma is there for the first reason, it should be heavily documented.
Another alternative reason for these to be in a code base... Its an accident.
This is a very handy tool for turning off the optimizer on a specific file whilst debugging - as Ray mentioned above.
If changelists are not reviewed carefully before committing, it is very easy for these lines to make their way into codebases, simply because they were 'accidentally' still there when other changes were committed.
I have used this exclusively to get better debug information in a particular set of code with the rest of the application is compiled with the optimization on. This is very useful when running with a full debug build is impossible due to the performance requirement of your application.
I know this is an old topic, but I would add that there is another reason to use this directive - though not relevant for most application developers.
When writing device drivers or other low-level code, the optimizer sometimes produces output that does not interact with the hardware correctly.
For example code that needs to read a memory-mapped register (but not use the value read) to clear an interrupt might be optimized out by the compiler, producing assembly code that does not work.
This might also illustrate why (as Angew notes) use of this directive should be clearly documented.