문제

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 ?

도움이 되었습니까?

해결책

You can just use &= with a boolean flag:

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

다른 팁

Just return early, since no additional code executes if ok becomes false:

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

    return (...);
}

This is another reason why exceptions are better than error codes: if you don't handle them, you don't spaghettify code for normal code paths.

You can use &= operator which is equal because bool is 1 bit type and all arithmetic operators works.

try using:

&=

instead of &&=

Alternatively you can choose not to use return values.

Pass in an object, or function pointers to use for success or failure.

E.g. with an object:

void onConditionOtherwise(BooleanAction& action)
{
    if (...) && (...) {
        action.success();
    } else {
        action.failure();
    }
}

The most standard way to do this is to return false when your condition is not met otherwise return true at the end of the method. So actually you don't even need that boolean variable.
Just use it like that:

bool myFunction()
{
    if (...) {

    } else return false;

    return true;
}

If you insist on using the boolean use the &= operator.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top