5

(This might be more of a common C question)

I want to test several conditions in an IF-sentence

if(variable) {            // fastest check
  if(register) {          // a bit slower
    if(read_peripheral) { // very slow check
      // [do something]
    }
  }
}

It seems obvious that I want to start with the fastest check, and move on to the slower ones afterwards, potentially avoiding to check them if the above was false.

Now since I need to check quite a few conditions, I'd like to know if the following is the same, or if all conditions will be evaluated prior to making a decision?

if(variable && register && read_peripheral) {
  // [do something]
}

1 Answers1

8

Putting them all in a single condition like that is absolutely fine. C/C++ uses "short circuit evaluation" which means it will stop as soon as it's determined the outcome. If everything is combined using logical AND operators (&&) then that means it will stop as soon as one of them evaluates to false.

For example:

 if (blah() && foo()) { ... }

If blah() returns false, it will never call foo() at all because it already knows the overall outcome is false.

The reverse happens with the logical OR operator (||):

 if (blah() || foo()) { ... }

If blah() returns true in this case, it won't call foo(). That's because it already knows the overall outcome is true.

Peter Bloomfield
  • 10,932
  • 9
  • 47
  • 87