if loop with multiple conditions WORKING

i was writing a pid code for arduino line follower
1
2
3
4
5
  suppose an array: 1,0,1,1 //suppose input from ir sensor array
  and an if statement
  if(a[0]==1 && a[1]==1 && a[2]==1 && a[3]==1){
    do_this();
  }

My doubt:
in this situation, will the if go to check all the conditions or it will stop where it is wrong ?
i.e. a[0] is correct, a[1] is not correct.....now will the if check stop here and control moves out of if, or will the continue till the end(checking all the conditions) in if ?
Last edited on
> will the if go to check all the conditions or it will stop where it is wrong ?

The && operator causes short-circuit evaluation: https://en.wikipedia.org/wiki/Short-circuit_evaluation

&& guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

If the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression.

https://eel.is/c++draft/expr.log.and

It will check all conditions but convince yourself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
    int a[]{1,1,1,1}; // play around with these
    
    if( a[0]==1 && a[1]==1 && a[2]==1 && a[3]==1)
    {
        std::cout << "Bingo\n";
    }
    else
    {
        std::cout << "Not Bingo\n";
    }
    
    return 0;
}


PS wrt short circuit evaluation. Why would it bother continuing when all must be true, unless at least one is found to return false.
Last edited on
Topic archived. No new replies allowed.