7

Does an if-statement with an && operator check for the second parameter if the first one is false / NO?

Would the following be able to crash?

NSDictionary *someRemoteData = [rawJson valueForKey:@"data"];
if( [someRemoteData isKindOfClass:[NSDictionary class]] && someRemoteData.count > 0 ){
    //..do something
}

Please no simple yes or no answer, but explain why.

Roland Keesom
  • 8,180
  • 5
  • 45
  • 52
  • If Objective-C is like nearly all other languages in this regard, the answer is no it won't, since `&&` shortcuts. Similarly, `||` will stop evaluating when it finds a condition that is true. – fge Jan 15 '13 at 15:29

3 Answers3

21

No, it does not evaluate the expression after learning that the answer is going to be NO. This is called short-circuiting, and it is an essential part of evaluating boolean expressions in C, C++, Objective C, and other languages with similar syntax. The conditions are evaluated left to right, making the evaluation scheme predictable.

The same rule applies to the || operator: as soon as the code knows that the value is YES, the evaluation stops.

Short-circuiting lets you guard against invalid evaluation in a single composite expression, rather than opting for an if statement. For example,

if (index >= 0 && index < Length && array[index] == 42)

would have resulted in undefined behavior if it were not for short-circuiting. But since the evaluation skips evaluation of array[index] when index is invalid, the above expression is legal.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Objective-C uses lazy evaluation, which means that only the left operand is evaluated in your case.

Attila H
  • 3,616
  • 2
  • 24
  • 37
0

NO it does not. If the first statement fails the second is never checked so for example you can do this (ArrayList != null && ArrayList.size() > 0) and you will never get an error if the variable is not initialized.

Nickolaus
  • 4,785
  • 4
  • 38
  • 60