Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ short circuit evaluation w.r.t optimization

Tags:

c++

Simple question, but surprisingly hard to search for. For the statement A && B I know there is a sequence point between the evaluation of A and B, and I know that the order of evaluation is left-to-right, but what is a compiler allowed to do when it can prove that B is always false (perhaps even explicitly so)?

Namely, for function_with_side_effects() && false is the compiler allowed to optimize away the function call?

like image 984
Brandon Avatar asked Dec 05 '22 17:12

Brandon


1 Answers

A compiler is allowed to optimise out anything, as long as it doesn't break the as-if rule. The as-if rule states that with respect to observable behaviour, a program must behave as if it was executed by the exact rules of the C++ abstract machine (basically normal, unoptimised semantics of code).

Observable behaviour is:

  • Access to volatile objects
  • Writing to files
  • Input & output on interactive devices

As long as the program does the three things above in correct order, it is allowed to deviate from other source code functionality as much as it wants.

Of course, in practice, the number of operations which must be left intact by the compiler is much larger than the above, simply because the compiler has to assume that any function whose code it cannot see can, potentially, have an observable effect.

So, in your case, unless the compiler can prove that no action inside function_with_side_effects can ever affect observable behaviour (directly or indirectly by e.g. setting a flag tested later), it has to execute a call of function_with_side_effects, because it could violate the as-if rule if it didn't.


As @T.C. correctly pointed out in comments, there are a few exceptions to the as-if rule, when a compiler is allowed to perform optimisations which change observable behaviour; the most commonly encountered among these exceptions being copy elision. However, none of the exceptions come into play in the code in question.

like image 103
Angew is no longer proud of SO Avatar answered Dec 08 '22 07:12

Angew is no longer proud of SO