Search code examples
c++logical-operatorslogical-and

How to have both functions called with logical AND operator (&&) c++


Let's say I had two functions and a variable,

int number;

bool foo (void);
bool footoo (void);

And in each of these functions, some logic with the variable number takes place, such as:

number++;
return(rand()%2);

And then I call them like so:

if (foo() && footoo())
{
    cout << "Two foo true!"
}

Why aren't both functions being called and how can I guarantee both functions are called and increment number, regardless of return value?


Solution

  • In C (and included in C++ by default) the && operator is short-circuiting. This means that as soon as the condition is deemed false the other operand is not evalulated. It allows us to do things like if(ptr && ptr->value == 10) without having to do the pointer validity check before the value check in a separate if statement.

    If you want to run both functions, run both functions and save off the results:

    bool b = foo();
    if(foobar() && b)
    {
        // Stuff
    }