在 C++ 中同时分配和条件测试
我有三个返回整数错误代码的函数,例如,
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;
}
谢谢!
I have three functions that return integer error codes, e.g.
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);
I want to assign and test for error at the same time for brevity. Will the following work and be portable?
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;
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不抛出异常呢?
Why not throw an exception?
我不明白为什么你在函数的开头有
error &&
,但其余的应该做你想要的。标准保证了||
运算符的短路评估。但我认为它的风格很糟糕。编辑:根据您的评论,您需要将
error &&
替换为error ||
。我还要补充一点,这是使用异常而不是错误代码的一个很好的理由,它使您的代码更易于阅读。I don't understand why you have the
error &&
at the beginning of the function, but the rest should do what you want. Short circuit evaluation of the||
operators is guaranteed by the standard. I would consider it bad style though.Edit: Based on your comment, you would need to replace
error &&
witherror ||
. I will also add that this is a good reason to use exceptions rather than error codes, it makes your code so much easier to read.error
初始化为0
。因此&&
将始终计算为false
。因此if
条件的其他部分永远不会被评估。所以这段代码将不起作用。如果删除&&
条件,代码应该可移植地工作,因为标准保证了这种情况下的评估顺序。error
is initialized to0
.So the&&
will always evaluates tofalse
. So other parts of theif
condition are never evaluated. So this code will not work. If you remove the&&
condition the code should work portably as the standard guarantees the order of the evaluation in this case.是的,在
&&
与||
进行细微更改后,它就会起作用。但它太混乱了(在测试中使用=
很混乱),没有太多好处。您可以选择另一张海报建议的
exception
行,或者简单地将您检查的代码放入函数中并执行如下操作。我相信任何程序员都会很容易理解这里所做的事情。
Yes, after the minor change of
&&
with||
it will work. But it's just too confusing (using=
in tests is confusing) with not much benefit.You could go for
exception
line another poster suggested, or simply put your checked code inside function and do like below.I believe any programmer will easily understand what is done here.