Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 297
Pac0 Avatar asked Oct 18 '10 11:10

Pac0


People also ask

Does C do lazy evaluation?

Our example of compiling non-strictness Now, we need a strategy to compile the non-strict version of our program. Clearly, C cannot express laziness directly, so we need some other mechanism to implement this.

What languages use lazy evaluation?

Languages that support lazy evaluation are usually functional programming languages like Haskell, which is lazy by default. Some languages, like OCaml and Scheme, let you opt into lazy behavior. Other languages like Swift and Perl 6 support it only for lists.

What is lazy evaluation example?

Lazy evaluation is an evaluation strategy which holds the evaluation of an expression until its value is needed. It avoids repeated evaluation. Haskell is a good example of such a functional programming language whose fundamentals are based on Lazy Evaluation.

Is lazy evaluation always better?

The cost/benefit of using lazy evaluation decreases as the item being accessed becomes less likely to be accessed. Always using lazy evaluation also implies early optimization. This is a bad practice which often results in code which is much more complex and expensive that might otherwise be the case.


2 Answers

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

like image 106
codaddict Avatar answered Oct 28 '22 23:10

codaddict


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

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

like image 21
Pablo Santa Cruz Avatar answered Oct 28 '22 23:10

Pablo Santa Cruz