17 February 2012

Bit manipulation gasp, gasp

Call me an elitist if you want, but it still surprises me how reluctant programmers are to use basic bit operations.

As an example, let's say that you have a series of calls to functions that might return true or false and you want to call every single one of them but if one of them returns true you want to preserve that value at the expense of the other false values.

For such a problem I am more likely to encounter code written similar to this:
bool anyreturntrue = false;
for( a few calls )
    bool result = SomeFunction();
    if( !anyreturntrue && result)
        anyreturntrue = result;
return anyreturntrue;

rather than the more elegant:
bool anyreturntrue = false;
for( a few calls )
    anyreturntrue |= SomeFunction();
return anyreturntrue;

Should this really be considered wizardry?
I hope not.