0

Sorry for noob question.

If a condition is tested with or, and the first condition is met, are the further conditions tested?

For example, is "b" even tested in the following code?...

bool a = true;
bool b = false;
bool c = false;

if (a || b)
{
c = true;
}

... or is the test cut short as soon as the first condition is met?

(edit)

Sorry, I answered my own question with this code.

if (test1() || test2())
            {
                Console.WriteLine("Complete");
            }

static bool test1()
        {
            Console.WriteLine("test1");
            return true;
        }
        static bool test2()
        {
            Console.WriteLine("test2");
            return false;
        }

Edited by Suzie999: solved

4
Contributors
6
Replies
7
Views
5 Years
Discussion Span
Last Post by Suzie999
Featured Replies
  • 1
    ddanbe 2,525   5 Years Ago

    [url]http://msdn.microsoft.com/en-us/library/6373h346(VS.80).aspx[/url] Read More

  • 1

    Just FYI, if you don't want it short-circuited, use the single character versions of the operands: [code]if (test1() | test2()) { Console.WriteLine("Complete"); } static bool test1() { Console.WriteLine("test1"); return true; } static bool test2() { Console.WriteLine("test2"); return false; }[/code] Prints both test1 and test2 regardless of the return values. Read More

  • 1
    Narue 5,707   5 Years Ago

    [QUOTE]I dont understand ! how could an && condition be short circuited?[/QUOTE] If the left operand is false, there's no point checking the right operand. [ICODE](false && x)[/ICODE] is absolutely going to result in false regardless of x. Read More

0

If a condition is tested with or, and the first condition is met, are the further conditions tested?

&& and || are both short circuited. They'll stop evaluating when a definite result is achieved.

1

Just FYI, if you don't want it short-circuited, use the single character versions of the operands:

if (test1() | test2()) {
    Console.WriteLine("Complete");
}

static bool test1() {
    Console.WriteLine("test1");
    return true;
}
static bool test2() {
    Console.WriteLine("test2");
    return false;
}

Prints both test1 and test2 regardless of the return values.

0

@ Narue

I dont understand ! how could an && condition be short circuited?

I would have thought it would have to test both conditions on either side to make a conclusion.

Please excuse my bad lingo.

1

I dont understand ! how could an && condition be short circuited?

If the left operand is false, there's no point checking the right operand. (false && x) is absolutely going to result in false regardless of x.

0

Of course, Duh !

Thanks.

My excuse is, I was thinking only about positive return :icon_redface:

This question has already been answered. Start a new discussion instead.
Be sure to adhere to our posting rules.