Does bitwise-or guarantee an evaluation ordering?
Asked Answered
C

2

16

Say I have this code:

unsigned int func1();
unsigned int func2();
unsigned int func3();

unsigned int x = func1() | func2() | func3();

Does C++ guarantee that func1() will be called first, then func2(), and then func3()?

Or is the compiler allowed to call the functions in any order it feels like?

Also, is the compiler allowed to implement a short-circuit optimization here if it wants to? (e.g. if func1() returned ~0, could the compiler decide not to bother calling func2() or func3(), because it knows their return values can't possibly affect the value assigned to x?)

Carpic answered 20/5, 2011 at 23:29 Comment(1)
Not pertaining to the question, but to a now-deleted answer: Three downvotes without comment? Come on guys, share the knowledge, don't be silly. @Answerer: The first part of your answer is incorrect, sub-expressions may be evaluated in any order; this is likely why you were being downvoted.Edmonson
S
19

No, there is no guarantee which order the functions will be called in. Unlike ||, | does not imply a sequence point.

All functions in the expression must be called unless the implementation can determine that they have no side-effects and it can determine the result of the expression without actually calling one of the functions. The implementation can do this under the "as if" rule which allows the implementation to perform any optimization which cannot be observed or detected by a conforming program.

Swabber answered 20/5, 2011 at 23:34 Comment(0)
S
13

It will not short circuit. It may execute out of order.

"The direction of evaluation does not affect the results of expressions that include more than one multiplication (*), addition (+), or binary-bitwise (& | ^) operator at the same level."

Spheroidicity answered 20/5, 2011 at 23:33 Comment(1)
That's fair; just cite your source next time. :-]Paddlefish

© 2022 - 2024 — McMap. All rights reserved.