Jonathan Mee
Jonathan Mee

Reputation: 38919

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

The following is a questionable minimal, complete, verifiable example. This is not a question about how to improve this code. What I do want to know is whether the standard condones the use of short circuit operators outside a conditional, as is demonstrated in main.

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;
}

This works for both Visual Studio 2015 and gcc 5.1 without asserting.

Upvotes: 2

Views: 187

Answers (2)

dbush
dbush

Reputation: 223972

From the C++14 standard, section 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.

The standard says nothing regarding the context of where && is used. If the left hand side evaluates to false, the right hand side is not evaluated.

In this context, the result of the expression is thrown away, similarly to if you did this:

1;

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234715

It's not the job of the standard to condone coding styles.

There's nothing wrong with your writing getWeekday(index, Weekday) && getName(Weekday, Name);

A reader of your code will know that getName(Weekday, Name) will not be called if getWeekday(index, Weekday) evaluates to false.

Upvotes: 5

Related Questions