Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If-statement with && operator checks for 2nd value?

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.

like image 270
Roland Keesom Avatar asked Jan 15 '13 15:01

Roland Keesom


People also ask

What is if statement with an example?

if (score >= 90) grade = 'A'; The following example displays Number is positive if the value of number is greater than or equal to 0 . If the value of number is less than 0 , it displays Number is negative .

What is && in if statement?

The logical AND operator ( && ) returns true if both operands are true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool . Logical AND has left-to-right associativity.

How do you write an if statement?

An if statement is written with the if keyword, followed by a condition in parentheses, with the code to be executed in between curly brackets. In short, it can be written as if () {} .


2 Answers

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.

like image 82
Sergey Kalinichenko Avatar answered Oct 05 '22 18:10

Sergey Kalinichenko


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

like image 40
Attila H Avatar answered Oct 05 '22 17:10

Attila H