Search code examples
c++if-statementshort-circuiting

The evaluation of 'if' expressions


Consider I have the following:

edge some_edge;
std::priority_queue<edge> my_queue;

Is it safe to write such an 'if' even if the queue might be empty?

if ((my_queue.size() > 0) && (my_queue.top().weight < some_edge.weight)) {
    do_something;
}

What about this one?

if ((my_queue.top().weight < some_edge.weight) && (my_queue.size() > 0)) {
    do_something;
}

Does evaluating an expression in which 'and' is the operator between the operands stop if the left operand evaluates false?


Solution

  • An if statement in C++ is left to right associative and the logical boolean operators && and || are short circuiting, so yes, a statement like the following is safe because it is guaranteed that you check the size first (assuming no evil overloading of these operators):

    if(myqueue.size() > 0 && myqueue.top().whatever) {
        // ...
    }
    

    The reverse is not true however because you check the return value of size() after popping the queue.

    As an aside, std::priority_queue provides an empty() function that I/many would prefer over size() > 0, but that works too.

    if(!myqueue.empty() && myqueue.top().whatever()) {
        // ...
    }