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

Recommended Answers

All 6 Replies

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.

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.

@ 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.

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.

Of course, Duh !

Thanks.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.