In
computer programming, a
short circuit expression is one in which there are multiple
conditions, but one or more of them are not
evaluated because it's not
necessary in order to know the
statement's
truth or
falsehood.
For example, if I said "I'll give you this apple if you give me a quarter or let me borrow your pen", it doesn't matter whether or not you will let me borrow your pen if you're willing to give me a quarter. The expression can cease, with a value of true, as soon it's true that you will give a quarter--it is short circuited.
An "or" condition is short circuited as soon as an element is true.
If, however, I said "I'll give you this apple if you give me a quarter and let me borrow your pen", the expression would be false if you let me borrow your pen, but didn't give me a quarter. Every component of the expression must be true in order for the entire expression to be true.
An "and" condition is short cicuited as soon as an element is false.
Example in C:
if (a==0 && b==1) { ... }
/* b is not checked if a is false. Expression is false. */
if (a==0 || b==1) { ... }
/* b is not checked if a is true. Expression is true. */
Perl also short circuits:
if ($a==0 && $b==0) { ... }
Visual Basic, prior to .NET, however, does not!
a = Null
If Not IsNull(a) And a = "Hello" Then: a = "World"
This
code will fail with an "Invalid use of
null"
error, because it tried to see if a is 3, even though the IsNull check should have established that that was
impossible. You must nest your conditions:
If Not IsNull(a) then
If a = "Hello" then: a = "World"
EndIf
Visual Basic .Net introduces the AndAlso and OrElse operators, which permit short circuited comparisons:
If Not IsNull(a) AndAlso a = "Hello" Then: a = "World"
They
behave like normal
and and
or in every other way.