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.
Learn the fundamentals of controlling program flow in C++ using if statements, for loops, while loops, continue, and break