-4

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?

R Sahu
  • 204,454
  • 14
  • 159
  • 270
Aniss Be
  • 163
  • 8

2 Answers2

3

Is the order depend on if statement depend on compiler used?

No.

Could that code crash if ObjectPtr is NULL?

No.

The language guarantees that.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

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).

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720