Pac0
Pac0

Reputation: 23129

C : is there "lazy evaluation" when using && operator, as in 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?

Upvotes: 19

Views: 18526

Answers (4)

codaddict
codaddict

Reputation: 454922

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

Upvotes: 22

sharptooth
sharptooth

Reputation: 170479

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.

Upvotes: 3

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181270

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

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

Upvotes: 10

Jackson Pope
Jackson Pope

Reputation: 14640

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

Upvotes: 9

Related Questions