1
if(ptr != NULL && ptr->isSomething())
{
    ...
}

This doesn't cause a segfault when I run it; though could it possibly throw one?

Is it guaranteed for the && operator, that if the first condition is false, then it won't even evaluate the second one?

Angivare
  • 467
  • 5
  • 16
  • Yes, the evaluation of those expressions is guaranteed by the standard to be from left to right, and the right expression will not execute if the first returns anything falsey. – Cory Kramer Feb 17 '15 at 20:26
  • Though not if overloaded (needs at least one user-defined type): [Is there actually a reason why overloaded && and || don't short circuit?](https://stackoverflow.com/questions/25913237/is-there-actually-a-reason-why-overloaded-and-dont-short-circuit) – Deduplicator Feb 17 '15 at 20:28
  • It's guaranteed that your code will behave *as if* the right operand of `&&` is not evaluted if the left operand is false. That means, among other things, that any side effects will not occur. But for something like `if (x != 0 && x != 1)`, the compiler might generate code that evaluates both comparisons if that's more efficient than a conditional branch (as long as `x` is not `volatile`). – Keith Thompson Feb 17 '15 at 20:31

0 Answers0