在条件之外使用短路运算符是否合法?

Is it Legal to Use Short Circuit Operators Outside a Conditional?

以下是有疑问的minimal, complete, verifiable example这不是关于如何改进此代码的问题。我想知道的是标准是否允许在条件之外使用短路运算符,如 [=11] 中所示=].

enum weekday {
    SUNDAY,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    WEEKDAY_SIZE
};

bool getWeekday(int index, weekday& result) {
    result = static_cast<weekday>(index);

    return index >= 0 && index < static_cast<int>(WEEKDAY_SIZE);
}

bool getName(weekday& index, string& result) {
    switch (static_cast<weekday>(index)) {
    case SUNDAY:
        result = "Sunday";
        break;
    case MONDAY:
        result = "Monday";
        break;
    case TUESDAY:
        result = "Tuesday";
        break;
    case WEDNESDAY:
        result = "Wednesday";
        break;
    case THURSDAY:
        result = "Thursday";
        break;
    case FRIDAY:
        result = "Friday";
        break;
    case SATURDAY:
        result = "Saturday";
        break;
    default:
        assert("Short Circut Failed");
        return false;
    }
    return true;
}

int main() {
    const int index = 0;
    weekday Weekday;
    string Name;

    getWeekday(index, Weekday) && getName(Weekday, Name);

    cout << Name << endl;
}

这适用于 Visual Studio 2015 和 gcc 5.1,无需断言。

宽恕编码风格不是标准的职责。

你写的没有问题getWeekday(index, Weekday) && getName(Weekday, Name);

您的代码的 reader 将知道如果 getWeekday(index, Weekday) 的计算结果为 false,则不会调用 getName(Weekday, Name)

From the C++14 standard,第 5.14 节:

1 The && operator groups left-to-right. The operands are both contextually converted to bool (Clause 4 ). The result is true if both operands are true and false otherwise. Unlike & , && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

2 The result is a bool . If the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression.

标准没有说明使用 && 的上下文。如果左侧评估为 false,则不评估右侧。

在此上下文中,表达式的结果被丢弃,类似于您这样做:

1;