Conditionals and Loops

Short-Circuit Evaluation Order

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved