compilation - C++ compiler optimizations and short-circuit evaluation -


here code :

b = f() || b; 

the function f() has side effect , must executed. normally, right operand can short-circuited , code should work. afraid compilators reverse 2 operands, since it's more efficient short-circuit function evaluation rather simple variable evaluation. know g++ -o3 can break specifications, don't know if code can affected.

so, code risk-free?

i knew is short-circuiting logical operators mandated? , evaluation order? question compilers optimizations, didn't know can't break standards (even if strange).

but afraid compilators reverse 2 operands

these expressions must evaluated left-to-right. covered in standard operators &&, ||, ?, , ,. mention order, enforced sequence points.

§5.14.1 (logical and)

the && operator groups left-to-right. operands both contextually converted bool (clause 4). result true if both operands true , false otherwise. unlike &, && guarantees left-to-right evaluation: second operand not evaluated if first operand false.

§5.15.1 (logical or)

the || operator groups left-to-right. operands both contextually converted bool (clause 4). returns true if either of operands true, , false otherwise. unlike |, || guarantees left-to-right evaluation; moreover, second operand not evaluated if first operand evaluates true.

§5.16.1 (conditional operator)

conditional expressions group right-to-left. first expression contextually converted bool (clause 4). evaluated , if true, result of conditional expression value of second expression, otherwise of third expression. 1 of second , third expressions evaluated. every value computation , side effect associated first expression sequenced before every value computation , side effect associated the second or third expression.

§5.19.1 (comma operator)

the comma operator groups left-to-right. pair of expressions separated comma evaluated left-to-right; left expression discarded value expression (clause 5). every value computation , side effect associated left expression sequenced before every value computation , side effect associated right expression. type , value of result type , value of right operand; result of same value category right operand, , bit-field if right operand glvalue , bit-field. if value of right operand temporary (12.2), result temporary.

regarding concern optimizations violating order, no compilers not allowed change order. compilers must first , foremost (try to) follow standard. then can try make code faster. may not violate standard sake of performance. undermines entire premise of having standard.


Comments

Popular posts from this blog

c# - Where does the .ToList() go in LINQ query result -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -