mardi 8 janvier 2019

Is it guaranteed that bitwise "and" for bool does not short circuit?

I recently came across a code snippet that looked like this:

bool MyClass::do_work()
{
    bool success = true;
    for (auto const& worker : m_workers)
    {
        success &= worker.do_work();  // worker.do_work() returns a bool
    }
    return success;
}

If I understand it correctly, the function returns true if all workers return true and it returns false if any worker returns false. However, it always evaluates all workers (which is desired). There is no short-circuit evaluation involved, since the bitwise operator &= was used and not the logical operator &&.

Is this behavior guaranteed? To be exact, is it guaranteed that bitwise & always evaluates both operands, even if they are of type bool? I came across many SO answers regarding guaranteed short-circuit evaluation for &&, but none of them state that there is guaranteed non-short-circuit evaluation for &.

If this behavior is guaranteed, is this a good programming style? It took me more than a quick glance to understand the function, because I have not seen this style before, and at first I was confused whether short-circuit evaluation was involved or not.

Is there a better alternative than the following?

bool MyClass::do_work()
{
    bool success = true;
    for (auto const& worker : m_workers)
    {
        if (!worker.do_work())
        {
            success = false;
        }
    }
    return success;
}

Aucun commentaire:

Enregistrer un commentaire