9

Suppose I have two expressions left/right of || operator. I find if left expression is true, the right operator will never be called. For example, in my below code, when getRand returns true, I found Foo will never be called. I tested on XCode on Mac OSX, and wondering if it is a reliable feature of C++ we could rely on -- if left part of || is true, right part will never be called, or it is a special feature just for specific platform (e.g. OSX with XCode)? Post my code below, thanks.

bool Foo()
{
    std::cout << "I am called!\n";
    return false;
}

bool getRand()
{
    int random_variable = std::rand();
    std::cout << random_variable << '\n';

    return random_variable % 2 == 1;
}

int main(int argc, const char * argv[]) {

    if (getRand() || Foo())
    {
        std::cout<<"Hello World \n";
    }

    return 0;
}

thanks in advance, Lin

Lin Ma
  • 9,739
  • 32
  • 105
  • 175
  • 2
    `wondering if it is a reliable feature of C++ we could rely on` Yes, it is. – Matt Dec 02 '15 at 08:22
  • 2
    && also have short circuit evaluation, if first argument is false – sp2danny Dec 02 '15 at 08:26
  • 2
    Short circuit evaluation is a reliable feature _most of the time_. It won't work if the used type has an overloaded && operator. Primitive types like `bool` are safe. – kolrabi Dec 02 '15 at 08:36

3 Answers3

10

Yes, it is a guaranteed feature called short circuit evaluation.

Likewise, an expression false && expression will never evaluate the right expression.

wallyk
  • 56,922
  • 16
  • 83
  • 148
8

wondering if it is a reliable feature of C++ we could rely on -- if left part of || is true, right part will never be called?

Yes, for builtin operator.

From the standard, $5.15/1 Logical OR operator [expr.log.or] (bold by me)

The || operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). It returns true if either of its operands is true, and false otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.

And note that the overload of operator|| will lose this special property.

Logical operators (bold by me)

Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both operands.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1

Since its one choice or another there is no need for the second part to be evaluated, is not platform dependant is a language feature.

Netwave
  • 40,134
  • 6
  • 50
  • 93