We know that logical-AND operator (&&
) guarantees left-to-right evaluation.
But I am wondering if the compiler optimizer can ever reorder the me
But I am wondering if the compiler optimizer can ever reorder the memory access instructions for *a and b->foo in the following code, i.e. the optimizer writes instructions that try to access *b before accessing *a.
if (*a && b->foo) { /* do something */ }
The C semantics for the expression require that *a
be evaluated first, and that b->foo
be evaluated only if *a
evaluated to nonzero. @Jack's answer provides the basis for that in the standard. But your question is about optimizations that compiler performs, and the standard specifies that
The semantic descriptions in this International Standard describe the behavior of an abstract machine in which issues of optimization are irrelevant.
(C2013, 5.1.2.3/1)
An optimizing compiler can produce code that does not conform to the abstract semantics if it produces the same external behavior.
In particular, in your example code, if the compiler can prove (or is willing to assume) that the evaluations of *a
and b->foo
have no externally visible behavior and are independent -- neither has a side effect that impacts the evaluation or side effects of the other -- then it may emit code that evaluates b->foo
unconditionally, either before or after evaluating *a
. Note that if b
is NULL or contains an invalid pointer value then evaluating b->foo
has undefined behavior. In that case, evaluation of b->foo
is not independent of any other evaluation in the program.
As @DavidSchwartz observes, however, even if b
's value may be null or invalid, the compiler may still be able to emit code that speculatively proceeds as if it were valid, and backtracks in the event that that turns out not to be the case. The key point here is that the externally-visible behavior is unaffected by valid optimizations.