C : is there "lazy evaluation" when using && operator, as in C++?
Asked Answered
E

4

19

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?

Epiphenomenalism answered 18/10, 2010 at 11:59 Comment(7)
@Sean: Testing doesn't necessarily equal "guaranteed by the standard".Restless
Incidentally this not always true in C++. The expression: (next != NULL) may use an overloaded != operator on whatever type next is. That operator may return another type on which && is overloaded. And for overloaded && there is no built-in short-circuiting, so the expression on the RHS will be evaluated regardless of the LHS.Gush
@pmg: Why is this not lazy evaluation?Gallic
@codymanix: Lazy evaluation is about delaying computation until the point that the results are required. This is short-circuiting, to avoid undefined behaviour (like deferencing a null pointer).Restless
Hmmm ... looks like some people call that short-circuiting lazy evaluation ( c2.com/cgi/wiki?LazyEvaluation ). I don't agree: to me lazy evaluation is "get ready to evaluate something but don't do it just now"; short-circuiting is "if it's ok do something right now, otherwise don't ever do it"Larkspur
@oli: By your definition, short circuiting is lazy evaluation, too. Avoiding access to uninitialized values is just a side effect of it which is often used.Gallic
@codymanix: I guess it's a matter of definition. I agree with pmg's definition...Restless
T
22

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

Thundershower answered 18/10, 2010 at 12:2 Comment(0)
C
10

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

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

Churrigueresque answered 18/10, 2010 at 12:0 Comment(0)
S
9

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

Sudatory answered 18/10, 2010 at 12:0 Comment(2)
Correction: It's definitely true in C, so it should be true in C++.Zhukov
@Zhukov - that's no correction. C++ and C are covered by standards, and this answer is correct about what both standards say (for built-in types in C++)Gush
L
3

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.

Lifelong answered 18/10, 2010 at 12:1 Comment(1)
it's called short circuit evaluation, lazy evaluation is something elseKuebbing

© 2022 - 2024 — McMap. All rights reserved.