我可以使用 &= 阻止函数执行吗?
示例代码如下:
bool result;
result = Operation1();
result &= Operation2();
result &= Operation3();
return result;
目的是确保如果任何函数返回 false,则不会调用后面的函数。这个语法正确还是我需要做 result = result &&操作2();
?
Example code follows:
bool result;
result = Operation1();
result &= Operation2();
result &= Operation3();
return result;
The intention is to ensure that, if any of the functions returns false, the functions that follow are not called. Is this syntax correct or do I need to do result = result && Operation2();
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您的意思是逻辑“与”而不是按位(我怀疑是这样,因为您使用的是
bool
),请使用短路:函数将从左到右计算,直到其中之一返回
false
,那么其余部分将不会被评估。If you mean a logical "and" rather than bitwise (I suspect so, since you're using a
bool
), use short circuiting:The functions will be evaluated left-to-right until one of them returns
false
, then the rest will not be evaluated.代码的短路版本(不需要结果变量,因为您立即返回它):
或者,如果表达式确实像本示例中一样短:
如果示例代码不具有代表性,并且您需要该变量一些未说明的原因:
Short-circuiting version of your code (no need for the result variable as you immediately return it):
Or, if the expressions are really as short as they are in this sample:
If the sample code is not representative and you need the variable for some unstated reason:
&
执行按位与,因此实际上您正在尝试and
所有答案在一起(如果所有三个操作都成功则为 true,否则为 false)。这不提供短路评估,其中如果Operation1()
失败则不会调用Operation2()
,并且Operation3()
不会调用如果Operation2()
失败则调用。&
does a bitwise and, so in effect you are trying toand
all your answers together (true if all three operations are successful, false otherwise). This does not provide short circuit evaluation whereOperation2()
isn't called ifOperation1()
fails, and whereOperation3()
isn't called ifOperation2()
fails.您的方法的问题是我不相信
true
必须始终具有相同的值。例如,如果一个操作返回 2,另一个操作返回 4,那么您 &这些加起来就是 0,或者false
。即使它们都返回 true,我也不知道标准中是否有任何具体保证它们将具有相同的按位模式。实际上,他们可能会……但是……?因此,我会坚持使用
&&
运算符,除非您使用积分并确保 opX() 始终返回某个值为 true 的值,另一个值为 false 的值,这样& =
运算符保证能够达到您的预期。此外,使用
&
您不会出现短路。The problem with your method is that I don't believe
true
has to always end up being the same value. If one op returned 2, another 4, for example, and you & those together you get 0, orfalse
. Even if they all returntrue
I don't know that there's any specific guarantee in the standard that they'll have the same bitwise pattern. Practically speaking, they probably will...but...?So I'd stick with the
&&
operator unless you work with integrals and make sure that opX() always returns a certain value for true and another for false such that the&=
operator is guaranteed to do what you expect.Furthermore, with
&
you don't get short circuiting.我通常将这种模式写为:
I generally see this pattern written as: