我有类似这样的代码:
return ( check1() && check2() && check3() && check4() );
除了返回一个值(例如打印输出)之外,不同的检查函数还可以做其他事情。似乎这些checkX
函数是按顺序运行的,只要一个返回 0,其余的就不会运行。这样做是有道理的。确保每个函数运行而不考虑其他返回值的最佳方法是什么(在 C++ 代码中)?
我有类似这样的代码:
return ( check1() && check2() && check3() && check4() );
除了返回一个值(例如打印输出)之外,不同的检查函数还可以做其他事情。似乎这些checkX
函数是按顺序运行的,只要一个返回 0,其余的就不会运行。这样做是有道理的。确保每个函数运行而不考虑其他返回值的最佳方法是什么(在 C++ 代码中)?
bool ret1 = check1();
bool ret2 = check2();
bool ret2 = check3();
bool ret4 = check4();
return (ret1 && ret2 && ret3 && ret4);
使用按位和运算符
return ( check1() & check2() & check3() & check4() );
这将在返回之前进行每个调用。
Node: This is a hack and is not recommend.
一种解决方案可能是在 bool 变量中捕获每个函数的结果,并在所有 4 个变量上执行 chexk。
bool x1 = check1();
bool x2 = check2();
bool x3 = check3();
bool x4 = check4();
return (x1 && x2 && x3 && x3);
bool res = check1();
res &= check2();
res &= check3();
res &= check4();
return res;
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());