C 中的 AND/OR 链
我对此非常肯定,但为了安全起见:
C 标准是否保证 AND 链(A && B && ...)将从左到右进行评估,并且一旦出现0就停止评估?
OR 同样的问题。 (一旦出现 1)
我可以指望这用于其他 C 风格语言吗?
这段代码安全吗:
if (somePtr!=NULL && somePtr->someMember==123)
{
...
}
I'm pretty much positive about this, but just to be on the safe side:
Does the C standard guarantee that AND chains (A && B && ...) will be evaluated left to right, and that evaluation will stop as soon as there's a 0?
Same question for OR. (As soon as there's a 1)
Can I count on this for other C-style languages?
Is this code safe:
if (somePtr!=NULL && somePtr->someMember==123)
{
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,对于 C、C++ 和 C# 是有保证的。 对于启用“短路评估”的德尔福来说也是如此。
这是目前许多行代码所依赖的行为。
Yes, it is guaranteed for C, C++ and C#. The same goes for Delphi with "short curcuit evaluation" enabled.
This is behaviour numerous lines of code rely on to this moment.
是的,它由 C 和 C++ 标准化。
Yes, it is standardised by both C and C++.
是的,您对 C 中操作顺序的假设是正确的,并且代码片段将按预期工作。 我会根据具体情况采用其他“C 风格”语言。
Yes, your assumptions about the order of operations in C are correct and the code snippet will work as intended. I would take other "C-style" languages on a case-by-case basis.
是的,它确实。
我见过有人认为这不清楚,并用这种形式替换了 &&'s:
就我个人而言,我认为这有点难看。
Yes it does.
I have seen people who thought that was unclear, and replaced &&'s with this form:
Personally I think that's kinda ugly.