Speaking plainly, it means that when you use an if instruction that has 2 or more clauses, if the first condition is not met (when the conditions are connected by an AND operator) or if the first condition is met (when the conditions are connected by an OR operator), the program will not evaluate the second expression.
The short circuit evaluation is available for C, C++, Java, C# and VB (and most of the other programming languages. See this for the full list).
It is commonly used for:
- Checking before a division that the denominator is not equal to 0
- Checking if a pointer is allocated before doing some operation with the data that he is pointing to.
Also, short circuit evaluation helps optimizing the code since an if statement that contains 5 clauses will end very quickly if one condition is not respected (without continuing to evaluate the other clauses), so your program will run more quickly.
Division check example for C\C++, Java and C#:
int a = 0, b = 32; if ( (a != 0) && (b / a > 10) ) //Will not go here because a=0 else //Will go here without triggering an divide by zero error/exception
Division check example for VB.NET
Dim x, y As Integer x = 0 y = 32 If ( (x <> 0) AndAlso (x / y > 10) ) Then 'Will not go here because x=0 Else 'Will go here without triggering an division by zero exception End If
Pointer example for C\C++
//We shall assume that you have a structure/class with a field //(a public field in//case of C++) data. MyStruct *myStructPointer = NULL; if ( (myStructPointer!=null) && (myStructPointer.data == 5) ) //Will not go here because myStructPointer = null else //Will go here without triggering a null error/exceptionPointer (Reference) example for Java and C#
//We shall assume that you have a class containing //a public field called data. Xobject myObject = null; if ( (myObject!=null) && (myObject.data == 5) ) //Will not go here because myObject = null else //Will go here without triggering a null error/exceptionPointer (Reference) example for VB. NET
If ( (str <> Nothing) AndAlso (str.Equals("Bird") ) Then 'Will not go here because x=0 Else 'Will go here without triggering a null exception End If
In VB.NET the short circuit OR operator is OrAlso.
- C++\C#\Java : & instead of && and | instead of ||
- Java has also : and instead of && and or instead of ||
- VB.NET : and instead of andAlso and or instead of orAlso
- C doesn't have "eager" operators and all evaluation is done short-circuit only.
"Eager" operators are mostly used when your second condition consists of a function that modifies some of your other variables (but this corresponds in most cases to a bad programming style).
No comments:
Post a Comment
Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!