Does the if statement with the && operator check for a second value?

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

Can a crash happen:

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

Please, not a simple answer β€œyes” or β€œno”, but explain why.

+6
source share
3 answers

No, he does not evaluate the expression after studying that the answer will be NO . This is called short-circuited, and it is an important part of evaluating Boolean expressions in C, C ++, Objective-C, and other languages ​​with similar syntax. Conditions are evaluated from left to right, which makes the assessment scheme predictable.

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

A short circuit protects against an invalid score in a single compound expression, rather than choosing an if . For instance,

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

would lead to undefined behavior if it were not intended to be a short circuit. But since the evaluation skips the evaluation of array[index] when index invalid, the above expression is legal.

+19
source

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

+3
source

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

0
source

All Articles