0

可能重复:
C++ 中是否存在非短路逻辑“与”?
C++ 逻辑 & 运算符

我有类似这样的代码:

return ( check1() && check2() && check3() && check4() );

除了返回一个值(例如打印输出)之外,不同的检查函数还可以做其他事情。似乎这些checkX函数是按顺序运行的,只要一个返回 0,其余的就不会运行。这样做是有道理的。确保每个函数运行而不考虑其他返回值的最佳方法是什么(在 C++ 代码中)?

4

5 回答 5

6
bool ret1 = check1();
bool ret2 = check2();
bool ret2 = check3();
bool ret4 = check4();

return (ret1 && ret2 && ret3 && ret4);
于 2012-10-24T20:34:42.883 回答
2

使用按位和运算符

return ( check1() & check2() & check3() & check4() );

这将在返回之前进行每个调用。


Node: This is a hack and is not recommend.

于 2012-10-24T20:38:23.727 回答
1

一种解决方案可能是在 bool 变量中捕获每个函数的结果,并在所有 4 个变量上执行 chexk。

bool x1 = check1();
bool x2 = check2();
bool x3 = check3();
bool x4 = check4();
return (x1 && x2 && x3 && x3);

于 2012-10-24T20:36:07.793 回答
1
bool res = check1();
res &= check2();
res &= check3();
res &= check4();
return res;
于 2012-10-24T21:01:50.960 回答
0

If you don't care about the sequence in which the functions run, you could use:

return (check1() + check2() + check3() + check4()) == 4;

Another possibility would be to use pointers to functions, so you can invoke them in a loop:

typedef bool (*f)();

f checks[] = {check1, check2, check3, check4};

bool ret = true;
for (int i=0; i<4; i++)
     ret &= checks[i]();

return ret;

This doesn't help much for dealing with 4 functions, but if 4 is just a demo and there are really more (or there's a good possibility of that expanding), this makes it relatively easy to deal with a large number of functions when/if necessary.

If you cared more about conciseness than clarity, you could do something like this:

bool ret = check1();

return (ret &= check2()), (ret &= check3()), (ret & check4());
于 2012-10-24T20:53:38.463 回答