Short-Circuit Evaluation Order

In what order are the conditions evaluated in short-circuit evaluation?

In short-circuit evaluation, the conditions are evaluated from left to right until the overall result of the expression can be determined. The evaluation stops as soon as the result is known, without evaluating the remaining conditions.

For the logical OR operator ||, if any condition evaluates to true, the entire expression is true, and the remaining conditions are not evaluated. For example:

#include <iostream>

bool condition1() {
  std::cout << "Evaluating condition1\n";
  return true;
}

bool condition2() {
  std::cout << "Evaluating condition2\n";
  return false;
}

int main() {
  if (condition1() || condition2()) {
    std::cout << "At least one condition is true.\n";
  }
}
Evaluating condition1
At least one is true.

In this example, condition1() is evaluated first and returns true. Since the logical OR only requires one true condition, condition2() is not evaluated, and the program proceeds to execute the code block.

For the logical AND operator &&, if any condition evaluates to false, the entire expression is false, and the remaining conditions are not evaluated. For example:

#include <iostream>

bool condition1() {
  std::cout << "Evaluating condition1\n";
  return false;
}

bool condition2() {
  std::cout << "Evaluating condition2\n";
  return true;
}

int main() {
  if (condition1() && condition2()) {
    std::cout << "Both conditions are true.\n";
  } else {
    std::cout << "At least one is false.\n";
  }
}
Evaluating condition1
At least one is false.

In this case, condition1() is evaluated first and returns false. Since the logical AND requires all conditions to be true, condition2() is not evaluated, and the program executes the else block.

Short-circuit evaluation allows for more efficient execution by avoiding unnecessary evaluations and can be used to prevent potential errors, such as dividing by zero or accessing null pointers, by placing those checks first in the condition.

Conditionals and Loops

Learn the fundamentals of controlling program flow in C++ using if statements, for loops, while loops, continue, and break

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Using break in Nested Loops
How can I break out of nested loops using the break keyword?
Conditional Operator Precedence
What is the precedence of the conditional (ternary) operator compared to other operators?
Condition in a do-while Loop
Is it possible to have a condition that always evaluates to false in a do-while loop?
Detecting Infinite Loops
How can I detect and prevent infinite loops in my C++ code?
Scope of Loop Variables
What is the scope of variables declared within the initialization statement of a for loop?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant