Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 236
James Hurley Avatar asked Dec 12 '22 12:12

James Hurley


1 Answers

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
}
like image 149
Mark B Avatar answered Dec 14 '22 02:12

Mark B