tags:

views:

155

answers:

2

If you have a C function which returns an integer, you could write a statement like this:

MyInt &= MyFunc();

...where we're using the bitwise-AND assignment operator.

The question is: is MyFunc() guaranteed to be executed, even if MyInt equals zero?

Likwise, if we used the bitwise-OR assignment operator (|=), would MyFunc() always be executed, even if MyInt were set to all ones?

Put another way: is lazy evaluation permitted in C for bitwise operators?

+8  A: 

No. Bitwise operators are not short-circuited. MyFunc() execution is guaranteed regardless of the value of MyInt.

Mehrdad Afshari
+1  A: 
MyInt &= MyFunc();

is equivalent to:

MyInt = MyInt & MyFunc();

The language states that the & operator is not short-circuited. However, an optimiser could generate code not to call to the function if MyInt was zero and it was sure that the function had no side effects. I doubt any compilers acrtually do this, as the runtime test probably makes it a pessimisation.

anon
Except that `MyInt` is evaluated **once** (might matter when it's an expression with side-effects.)
Mehrdad Afshari
The thing on the LHS of the assignment won't be evaluated.
anon
Neil: consider `myMap["test"] |= 10;` where `myMap.operator[]` prints something. It'll get printed twice in the second form but once in the compound assignment form.
Mehrdad Afshari
@Mehrdad Consider that this question is tagged as C, not C++.
anon
Oops. Didn't notice. Surrendered.
Mehrdad Afshari
`gcc` actually does do this optimisation (in cases where it knows that `MyInt` is zero at compiletime, and that `MyFunc` has no sideeffects). You can tell `gcc` that an external function has no sideeffects using the `pure` attribute.
caf
isn't `pure` a C++0x feature? Even if not, it certainly isn't a C feature.
Carson Myers
Attributes are added to C++0X -- I don't remember if there is a pure attribute or not --, but it is a standardization of the attribute notions than some compilers already have. Including gcc. caf suggest here to use a gcc extension.
AProgrammer