2

我有三个返回整数错误代码的函数,例如

int my_function_1(const int my_int_param);
int my_function_2(const int my_int_param);
int my_function_3(const int my_int_param);

为了简洁起见,我想同时分配和测试错误。下面的工作和便携吗?

int error=0;
...
if ( error ||
     (error = my_function_1(val1) ||
      error = my_function_2(val2) ||
      error = my_function_3(val3)) ) {
   std::cout << "AN ERROR OCCURRED!!!" << std::endl;
}

谢谢!

4

4 回答 4

4

为什么不抛出异常?

void my_function_1(const int my_int_param);
void my_function_2(const int my_int_param);
void my_function_3(const int my_int_param);

try {
    my_function_1(...);
    my_function_2(...);
    my_function_3(...);
} catch(std::exception& e) {
    std::cout << "An error occurred! It is " << e.what() << "\n";
}
于 2010-09-17T16:02:57.977 回答
2

我不明白为什么你error &&在函数的开头有,但其余的应该做你想做的。||该标准保证了操作员的短路评估。不过,我会认为这是不好的风格。

编辑:根据您的评论,您需要替换error &&error ||. 我还要补充一点,这是使用异常而不是错误代码的一个很好的理由,它使您的代码更易于阅读。

于 2010-09-17T15:58:15.817 回答
0

error被初始化为0。所以&&will 总是计算为false。所以if条件的其他部分永远不会被评估。所以这段代码不起作用。如果您删除&&条件,代码应该可以移植,因为标准保证了在这种情况下评估的顺序。

于 2010-09-17T15:58:12.133 回答
0

是的,在对其进行细微更改后&&||它将起作用。但这太令人困惑了(=在测试中使用令人困惑)并没有太大的好处。

您可以选择exception另一张海报建议的路线,或者只是将您检查的代码放入函数中,然后像下面那样做。

int checked(){
    int error = 0;
    error = my_function_1(val1); if (error) return error;
    error = my_function_2(val1); if (error) return error;
    error = my_function_3(val1); if (error) return error;
    return error;
}

我相信任何程序员都会很容易理解这里做了什么。

于 2010-09-17T17:05:42.717 回答