-3

a - checks whether input is defined for function b

if (a) {
    if (b) {
        /* ... */
    }
}

clearly works. Does the &&-operator always check the first input?

if (a && b) {
    /* ... */
}

Would this possibly cause undefined behaviour from b function?

lupz
  • 3,620
  • 2
  • 27
  • 43
BorticFan
  • 7
  • 3

3 Answers3

2

Yes, the built-in && short-circuits.

So, if a is false, b will not be evaluated. This is guaranteed, unless there is an overload of operator&&(type of a, type of b).

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

In the expression a && b, assuming && is the built-in operator and not an overloaded one, b is only evaluated if a evaluates to true.

That's why you can write things like if (a != nullptr && *a).

We call this short circuiting. || also has the property.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

As Bathsheba said, if your code is

if (a && b) {
    //...
}

Then b will only be checked if a results to true. This is because the && operator is a so-called shortcut operator. The same goes for the logical OR (||).

if (a || b)//...

In this case, however, b would only be evaluated if a results to false.

These are not to be confused with the bitwise operators (& and |), which check both values regardless.

SimonC
  • 1,547
  • 1
  • 19
  • 43
  • Not sure I've ever heard it called a "shortcut operator". If anything, some people call `x += 42` a "shortcut operator" (versus `x = x + 42`) though even that doesn't seem to be widespread. – Lightness Races in Orbit Dec 20 '18 at 11:54
  • Sorry, my bad. Shortcircuit operator. I typed the answer on my phone, I guess autocorrect got me there. – SimonC Dec 20 '18 at 11:59