Here is my code :
b = f() || b;
The function f()
has side effect and it must be always executed. Normally, only the right operand can be short-circuited and this code should work. But I am afraid some compilators reverse the two operands, since it's more efficient to short-circuit a function evaluation rather than a simple variable evaluation. I know that g++ -O3 can break some specifications, but I don't know if this code can be affected.
So, is my code risk-free?
I knew Is short-circuiting logical operators mandated? And evaluation order? but my question was about compilers optimizations, I didn't know that they can't break the standards (even if this would be strange).
These expressions must be evaluated left-to-right. This is covered in the standard about the operators
&&
,||
,?
, and,
. They specifically mention the order, as well as enforced sequence points.§5.14.1 (Logical AND)
§5.15.1 (Logical OR)
§5.16.1 (Conditional operator)
§5.19.1 (Comma operator)
Regarding your concern about optimizations violating this order, no compilers are not allowed to change the order. Compilers must first and foremost (try to) follow the standard. Then they can try to make your code faster. They may not violate the standard just for the sake of performance. That undermines the entire premise of having a standard.