C : is there “lazy evaluation” when using && operator, as in C++?

好久不见. 提交于 2019-11-26 17:11:43

问题


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?


回答1:


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




回答2:


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

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




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/3958864/c-is-there-lazy-evaluation-when-using-operator-as-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!