0

(This following is related to microcontroller programming)

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]
}
Lundin
  • 195,001
  • 40
  • 254
  • 396
Allan Nørgaard
  • 284
  • 2
  • 11
  • I'm asking if the IF statement will evaluate every condition, even if the first one fails. I don't see the relation to the question you link – Allan Nørgaard Jan 29 '15 at 14:57
  • The logical AND and OR operators (`&&` and `||`) do [short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation). So in your second code snippet, if `variable` is "false" then the other expressions will not be evaluated. A good optimizing compiler will most likely generate similar (or even the same) code for both examples you show. – Some programmer dude Jan 29 '15 at 14:58
  • Also note that the two code snippets are equal *only* if you don't do anything between or after any of the nested `if` statements. – Some programmer dude Jan 29 '15 at 14:59

1 Answers1

7

From chapter 6.5.13, Paragraph 4, C99 standard, regarding Logical AND operator [&&]

the && operator guarantees left-to-right evaluation

and

If the first operand compares equal to 0, the second operand is not evaluated.

So, your second code is as efficient as your first one and also comes with better readability.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261