If I have a C statement with the logical OR operator || :
if (isFoo() || isBar())
blah();
I know the compiler generated code will not execute isBar() if isFoo() returns true.
What about the bitwise OR operator | ?
if (isFoo() | isBar())
blah();
Likely this is sloppy writing, or if the writer requires isBar() and isFoo() to be both be executed because of those functions’ side-effects, then they should express their intent more clearly. Or maybe I’m wrong and this is an acceptable C/C++ idiom.
Nevertheless, will a decent compiler actually generate a temporary variable to do the bitwise or’ing of the return values of isFoo() and isBar() when optimizations are turned on? Or will it instead convert the bitwise OR operation into a logical OR operation in order to allow short-circuit’ing of the boolean expression in order to prevent the calling of isBar()?
The compiler is free to optimize the “or’ing” however it wants, but the program must behave as if both function calls actually happen, and they could happen in either order. This actually bit me once when I naively changed a
||to|because I needed both calls to happen, but forgot that the right-hand call could happen before the left-hand one and that the right-hand one depended on the results of the left-hand one…and the bug didn’t show up until somebody decided to try compiling my code withpccinstead ofgcc. So my advice is to be careful with stuff like this and write out what you mean clearly.Finally, note that I said “as if both function calls actually happen”, because in the case where the compiler can determine that a function has no side effects, it might optimize out the right-hand side if the left-hand side resulted in a nonzero value.