Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ logical expression optimization

Is it okay for me to presume in C or C++ or JavaScript or any other modern language that if I do…

bool funt1(void) {…}
bool funt2(void) {…}
if (funt1() && funt2()) {Some code}

… Am I guaranteed that both functions get called or if funt1 returns false can the compiler bail on me and never call funt2?

like image 534
Chris Young Avatar asked Sep 11 '26 06:09

Chris Young


2 Answers

In C, C++, and Javascript, the logical operators && and || short circuit, i.e. in A && B, A is evaluated first and B evaluated if and only if A returned true. Similarly, in A || B, B is evaluated if and only if A returned false. These are guaranteed by the language standards and apply even if B has side effects (in fact, this can be used to control those side effects).

In C++, these rules only apply to the logical operators applied to built in types, but not to user-defined logical operators of the same name. However, in your code snippet, two bool are compared, so this cannot be a user-defined &&.

like image 76
Walter Avatar answered Sep 12 '26 19:09

Walter


There is a pitfall in C++: If the first and the second function return objects and both are needed for the logical operation, there is no short circuit.

#include <iostream>

struct A {};
struct B {};

bool operator || (const A&, const B&) { return true; }

A a() { std::cout << "A\n"; return A(); }
B b() { std::cout << "B\n"; return B(); }

bool f() { std::cout << "f\n"; return true; }
bool g() { std::cout << "g\n"; return true; }

int main(int argc, char* argv[])
{
    if(a() || b());
    if(f() || g());
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!