Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Objective-C use short-circuit evaluation?

I tried something along the lines of:

if(myString != nil && myString.length) { ... }

And got:

-[NSNull length]: unrecognized selector sent to instance

Does Objective-C not short-circuit after the first condition fails?

like image 803
kwcto Avatar asked Jan 13 '10 22:01

kwcto


People also ask

Does C have short-circuit evaluation?

In imperative language terms (notably C and C++), where side effects are important, short-circuit operators introduce a sequence point – they completely evaluate the first argument, including any side effects, before (optionally) processing the second argument.

Which type of operators use short-circuit evaluation?

So when Java finds the value on the left side of an || operator to be true, then Java declares the entire expression to be true. Java's && and || operators use short circuit evaluation.

What is short-circuit evaluation give an example?

Short-Circuit Evaluation: Short-circuiting is a programming concept in which the compiler skips the execution or evaluation of some sub-expressions in a logical expression. The compiler stops evaluating the further sub-expressions as soon as the value of the expression is determined.

Does && use short-circuit evaluation C++?

In C++, both && and || operators use short-circuit evaluation.


1 Answers

Objective-C does support short-circuit evaluation, just like C.

It seems that in your example myString is NSNull and not nil, therefore myString != nil is true.

NSNull is a singleton and is used to represent nil where only objects are allowed, for example in an NSArray.

Btw, normally, people write if (!myString && myString.length == 0). Comparing to nil is quite ugly. Also, I'd compare the length to 0. That seems to be more clear.

like image 173
Georg Schölly Avatar answered Sep 20 '22 21:09

Georg Schölly