-1

Suppose I had an if statement in a method like so:

if ( foo() || bar() ) {
    return true;
}

Would both foo() and bar() both be processed entirely before assessing whether to execute the code within, or as soon as one condition satisfies the if?

My reason for asking is that my equivalents of the foo() and bar() methods are fairly computationally expensive functions, and if foo() alone satisfied the if conditions I would not want to execute bar(). As such, my current code is along the lines of:

if ( foo() ) {
    return true;
}
if ( bar() ) {
    return true;
}

Is this necessary, or would the logical OR separated function behave as a require?

Quetzalcoatl
  • 3,037
  • 2
  • 18
  • 27
  • A comment explaining the downvote would be nice - is my question really unclear or not useful? I was unaware of short-circuiting and surely this question could prove useful to someone else who was also unaware. – Quetzalcoatl Oct 23 '12 at 16:05

3 Answers3

7

&& and || are short-circuiting in all 3 languages AFAIK, so if foo() evaluates to true, bar() will not be called.

5.15 Logical OR operator [expr.log.or]

1) 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. (emphasis mine)

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

If any one of them will be true, it will not proceed further. That is call Short Circuit Evaluation.

If foo() resolves to true, the next method bar() will not be executed in the if statement. The condition will resolve to true.

Check || Operator (C# Reference) - MSDN

The operation

x || y

corresponds to the operation

x | y

except that if x is true, y is not evaluated because the OR operation is true regardless of the value of y. This concept is known as "short-circuit" evaluation.

Habib
  • 219,104
  • 29
  • 407
  • 436
1

I got little curious and wrote a small program to ascertain what should happen.

class Program
    {
        static void Main(string[] args)
        {

            if (foo() || bar())
            {
                Console.WriteLine("Either Foo or Bar returned true");
            }
            Console.ReadKey();
        }
        public static bool foo()
        {
            Console.WriteLine("I am in Foo");
            return true;
        }
        public static bool bar()
        {
            Console.WriteLine("I am in Bar");
            return false;
        }

    }

This just returned

I am in Foo
Either Foo or Bar returned true

Means, if first evaluation is true, it will NOT go for second evaluation and it goes left to right.

-Milind

Milind Thakkar
  • 980
  • 2
  • 13
  • 20