lundi 6 mai 2019

C++ if statements: first condition superseding the second - UB or well defined?

Being a moderate time coder, I saw things like the following many times:

if (a != nullptr && a->data != nullptr) {
  // do something good with a and a->data
}

However, I never really referred to documentation regarding such a simple case.


To my mind, the following is happening:

  • First, a != nullptr is checked
  • Second, a->data != nullptr is checked

The thing now here is: if a != nullptr returns false and we have a conjunction via && then there's no point to check the second statement a->data != nullptr being true or false:

since the first statement results in a false expression, the code inside the if-statement will not be executed, we don't need to check the second expression


But recently I have returned to the question yet again:

Is if safe to have a construction like this: if (a != nullptr && a->data != nullptr) {}? Can it happen so that both* statements are checked and what I get is the nullptr dereference?

*- no multi-threading involved


What I'm asking is: is the above situation has a well defined behavior (and where can I find documentation for that) or this is generally UB that must be avoided? Is the behavior any different depending on the operating system (say, Windows vs. Linux-based)?

Aucun commentaire:

Enregistrer un commentaire