Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if the first part of an if-structure is false?

I was wondering what happens when a program processes an if-structure with multiple conditions. I have an idea, but I'm not sure about it. I'll give an example:

List<string> myTestList = null;
if (myTestList != null && myTestList.Count > 0)
{
    //process
}

The list is null. When processing the if statement, will it go from left to right exiting the if as soon as one condition is false?

I've tried it and seems to throw no errors, so I assume the above explains it, but I'm not sure.

like image 827
Terry Avatar asked May 19 '10 10:05

Terry


3 Answers

It is the && that is important. This is short-circuiting, so the Count is never evaluated; The conditions are evaluated left-to-right.

There is also a non-short-circuiting operator (&), but it is very rare to see in an if test; it is mainly intended for bitwise operations (on int etc).

From the spec:

Conditional logical operators

The && and || operators are called the conditional logical operators. They are also called the “short-circuiting” logical operators.

...

The && and || operators are conditional versions of the & and | operators:

  • The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is not false.
  • The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is not true.
like image 188
Marc Gravell Avatar answered Oct 07 '22 01:10

Marc Gravell


In most (but not all) modern languages, there is a feature called "short circuit boolean evaluation". This means that if the first part of an && condition is false, then the second part is not evaluated at all.

A similar feature applies to ||, where if the first part is true, the second part is not evaluated.

Note that this feature is not limited to if statements. The following is also valid and won't try to reference Count if myTestList is null:

bool b = myTestList != null && myTestList.Count > 0;
like image 32
Greg Hewgill Avatar answered Oct 07 '22 00:10

Greg Hewgill


It's short-circuited.

a && b

if a is false, b will not be evaluated. We can use this behavior because the expression will always be false.

Similarly,

a || b

if a is true, b will not be evaluated.

like image 40
kennytm Avatar answered Oct 07 '22 00:10

kennytm