Quick question. How the following code will perform order of check :
if ((NULL != ObjectPtr) && (ObjectPtr->isValid()) )
{
}
Is the order on if
-statement depend on compiler used? Could that code crash if ObjectPtr
is NULL
?
Quick question. How the following code will perform order of check :
if ((NULL != ObjectPtr) && (ObjectPtr->isValid()) )
{
}
Is the order on if
-statement depend on compiler used? Could that code crash if ObjectPtr
is NULL
?
Is the order depend on
if
statement depend on compiler used?
No.
Could that code crash if
ObjectPtr
isNULL
?
No.
The language guarantees that.
In C++, the &&
operator is guaranteed to be short-circuiting. This means that the left-hand operand is checked first, and if it is false, none of the right-hand operand is evaluated.
So your code is safe and will not perform member access through the NULL pointer.
Similarly, ||
is also short-circuiting and will not evaluate any of its right-hand operand if the left operand is true.
With boolean operands, the bitwise operators &
and |
give the same result as the logical operators &&
and ||
, but the bitwise operators do not short-circuit and their right-hand operand is always evaluated (possibly before the left-hand one).
Also as Quentin mentions in a comment, user-provided overloads of these operators do not short-circuit, because they are actually function calls and have the evaluation order of function calls (all arguments evaluated before the call).