And operator in IF statement

I have an if statement that has two conditions, one is cheap to test, the other is comparatively expensive. If I separate them with an && and the first one fails, will it immediately pass over that if statement, or will it test the second condition anyway? In the case of the latter I'm thinking I should have a nested if statement instead?

For example :

1
2
3
4
5
6
7
8
bool expensiveCall() {
  // lots of code
  return true;
}

if( x < y && expensiveCall() ) {
  // do something
}


If the 'x < y' condition fails will it skip over testing expensiveCall()? Or instead should I do :

1
2
3
4
5
6
7
8
9
10
bool expensiveCall() {
  // lots of code
  return true;
}

if( x < y ) {
  if( expensiveCall() ) {
    // do something
  }
}


Thanks in advance
Last edited on
Hello kaprikawn,

Welcome to the forum.

Your answer is yes and yes,

Using && in an if statement means that both sides need to be true for the whole to be true. If the first part is false the second part is skipped because the whole can not be true so there is no need to go any farther.

The same concept holds for "x < y" if this is false then the then portion of the first if statement is skipped unless there is a matching else statement.

Someone else might say this better, but if there is anything you still do not understand let me know.

Hope that helps,

Andy
C/C++ uses the so called short-circuit to evaluate the expression. See:

http://en.cppreference.com/w/cpp/language/operator_logical
https://en.wikipedia.org/wiki/Short-circuit_evaluation

There might be a problem with order of evaluation if you have more expressions. So I would suggest to use the second concept.
C+ uses short-circuit evaluation for && and || operators, for exactly the reason that you're facing. It will avoid evaluating the right operand if the value of the left operand implies the value of the full expression.

This is a good segway into the importance of understanding the precedence of operators and the order of evaluation of operands. Precedence determines where the implicit parentheses are. For example, whether a + b * c is (a + b) * c or a + (b * c) (it's the latter).

Order of evaluation tells when the operands are evaluated. This is important when the operands are function calls or have side effects. For example, in f1() + f2(), does the program call f1() first or f2()? Usually the order of evaluation is unspecified. The program can evaluate f1() first, or f2(), or even both at the same time. The && and || operators are two of the few that actually do specify the order.
Topic archived. No new replies allowed.