C:是否存在“惰性评估”?当使用 &&运算符,如 C++ 中那样?
我想知道这看起来是否正确:
while((next !=NULL) && (strcmp(next->name, some_string) < 0) {
//some process
}
我的意思是,如果 next 是 NULL,那么编译器将不会测试表达式的第二部分?我听说 C++ 是这样的(但我什至不确定)。
有人可以确认我不会在某些编译器上遇到奇怪的错误吗?
I would like to know if this looks correct :
while((next !=NULL) && (strcmp(next->name, some_string) < 0) {
//some process
}
I mean, if next is NULL
, then the second part of the expression won't be ever tested by the compiler? I have heard that in C++ it's the case (but I'm not even sure of it).
Can someone confirm me that I won't get strange errors on some compilers with that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,
&&
是短路的,并且您使用正确。如果
next
是NULL
字符串比较将永远不会发生。Yes
&&
is short circuited and you are using it correctly.If
next
isNULL
string compare will never happen.是的,在 C++ 中可以使用短路
and
和or
运算符。这里是有关该主题的 C-faq 中回答的问题。
Yes, in C++ short circuit
and
andor
operators are available.Here's a question answered in the C-faq on the subject.
在 C 和 C++ 中都是如此。
It's definitely the case in both C and C++.
这将适用于惰性求值(如果第一个语句求值为“假”,则第二个语句不会求值),除非您的编译器非常不符合标准,甚至不能被命名为 C 编译器。该领域的数百万行代码依赖于此行为,因此您可以认为此行为只是有保证的。
This will work with lazy evaluation (the second statement not evaluated if the first one is evaluated to "false") unless your compiler is so non-standard compliant it can't even be named a C compiler. Millions lines of code in the field rely on this behavior, so you can think that this behavior is just guaranted.