C:是否存在“惰性评估”?当使用 &&运算符,如 C++ 中那样?

发布于 2024-09-27 14:15:28 字数 249 浏览 2 评论 0原文

我想知道这看起来是否正确:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

偷得浮生 2024-10-04 14:15:28

是的,&& 是短路的,并且您使用正确。
如果 nextNULL 字符串比较将永远不会发生。

Yes && is short circuited and you are using it correctly.
If next is NULL string compare will never happen.

窝囊感情。 2024-10-04 14:15:28

是的,在 C++ 中可以使用短路 andor 运算符。

这里是有关该主题的 C-faq 中回答的问题。

Yes, in C++ short circuit and and or operators are available.

Here's a question answered in the C-faq on the subject.

旧话新听 2024-10-04 14:15:28

在 C 和 C++ 中都是如此。

It's definitely the case in both C and C++.

捎一片雪花 2024-10-04 14:15:28

这将适用于惰性求值(如果第一个语句求值为“假”,则第二个语句不会求值),除非您的编译器非常不符合标准,甚至不能被命名为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文