如何使用逻辑AND运算符(&&)c ++调用这两个函数

Jam*_*ley 3 c++ logical-operators logical-and

假设我有两个函数和一个变量,

int number;

bool foo (void);
bool footoo (void);
Run Code Online (Sandbox Code Playgroud)

在每个函数中,number都会发生一些带变量的逻辑,例如:

number++;
return(rand()%2);
Run Code Online (Sandbox Code Playgroud)

然后我称他们为:

if (foo() && footoo())
{
    cout << "Two foo true!"
}
Run Code Online (Sandbox Code Playgroud)

为什么不调用这两个函数number?无论返回值如何,我如何保证调用和递增函数?

Mar*_*k B 7

在C中(默认情况下包含在C++中)&&运算符是short-circuiting.这意味着一旦条件被认为是假,则不评估其他操作数.它允许我们if(ptr && ptr->value == 10)在单独的if语句中进行值检查之前不需要执行指针有效性检查.

如果要运行这两个函数,请运行这两个函数并保存结果:

bool b = foo();
if(foobar() && b)
{
    // Stuff
}
Run Code Online (Sandbox Code Playgroud)