Search code examples
c++booleanlogical-operatorsstandards-compliance

Self logical and?


The answer may be obvious for some of you, but as I can't find the answer, I need to ask it. Oftenly, if a function has to return whether all was executed without problems, I use a boolean that track any failure.

bool myFunction()
{
    bool ok = true;
    if (...) {
        if (...) {
            ok = ...;
        }
        ok = ok && (...);
    }
    ok = ok && (...);
    return ok;
}

As no &&= exists, I use a lot this syntax : ok = ok && (...) ((...) can be a condition or a value). But I find this quite unelegant. Is there any C++ standard-compliant way to write this more concisely and elegantly ?


Solution

  • You can just use &= with a boolean flag:

    bool myFunction()
    {
        bool ok = true;
        if (...) {
            if (...) {
                ok &= ...;
            }
            ok &= ...;
        }
        ok &= ...;
        return ok;
    }