upashu2 wrote:
In C++ (a && b)
The first operand ( a) is completely evaluated and all side effects are
completed before continuing evaluation of the logical AND expression.
The second operand (b) is evaluated only if the first operand
evaluates to true (nonzero). This evaluation eliminates needless
evaluation of the second operand when the logical AND expression is
false. You can use this short-circuit evaluation to prevent
null-pointer dereferencing, as shown in the following example:
.
if ((obj != NULL) && (obj->someMethod()))
If obj is null (0), the right side of the expression is never
evaluated.
But there's a catch.
The correct answer is that righthand side of the && expression in the
sample code provided ( (obj->someMethod()))) may or may not be
evaluated even when objc != NULL is false. There is not enough in the
sample provided to answer for certain.
Only the built-in && operator is guaranteed not to evaluate the
righthand side of the expression if the lefthand side is false. A
user-defined && operator would always force an evaluation of the
righthand side of its expression since it is passed as a parameter to
the operator&& routine.
Since the code above omits obj's declaration, the && operator (and the
!= operator as well) could have been overloaed in the case that obj is
declared as some kind of a smart pointer type.
Greg