Can the compiler optimize the call to deal with possible side effects?

If there is C or C ++ code, for example:

if (func()) ; 

can the compiler optimize the function call func() if it cannot be sure if the function has any side effects?

Origin of my question: sometimes I call assert macros like this:

 if (func()) assert(0); 

if I want to make sure func() always called and that asssertion is not working in debug mode if func() returns the wrong value. But lately, I have been warned that my code does not guarantee that a function is always called.

+2
source share
2 answers

If the compiler cannot prove that optimizing a call on func does not change the observed behavior of your program, optimizations are not allowed.

Therefore, if the compiler cannot prove that the function call has no observable effect, the call will take place. Note that compilers can sometimes be smart, so if you want to be sure, make sure that the function does have a side effect. (On the other hand, if it’s not, you don’t care.)

This is commonly known as-if .

+10
source

(This is a C ++ answer. Ask a question for one programming language only , not two.)

No, a function that can have side effects cannot be optimized, because then you can “optimize” the side effects. And since "side effects" we really mean "what your program does," a compiler that is allowed to do such a thing will not be particularly useful. Therefore, the standard “as is” rule prevents the optimization you are talking about.

+3
source

All Articles