我进行了以下测试:
- (void)testExampleOther {
__block BOOL called = NO ;
NSInteger (^eval)(NSInteger) = ^NSInteger (NSInteger x) {
called = YES ;
return x ;
} ;
BOOL failed = NO ;
BOOL ok = NO ;
for (NSInteger i = 0 ; i < 256 ; ++i) {
ok &= eval(i) ;
if (ok) {
failed = YES ;
NSLog(@"bitwise & used as logic wise && failed for value: %d", i) ;
}
}
if (!failed) {
NSLog(@"All values 'x' from 0 to 255 returned NO for:\" BOOL ok = NO ; ok &= x ; \"") ;
}
if (called) {
NSLog(@"BUT x was evaluated even though it did not need to.") ;
}
}
这是相关的输出:
Test Case '-[JFBLib_Tests testExampleOther]' started.
2013-08-21 15:50:47.127 xctest[23845:303] All values 'x' from 0 to 255 returned NO for:" BOOL ok = NO ; ok &= x ; "
2013-08-21 15:50:47.127 xctest[23845:303] BUT x was evaluated even though it did not need to.
Test Case '-[JFBLib_Tests testExampleOther]' passed (0.000 seconds).
这似乎证实了这一点:
- 如果以 0(否)开头,则
x
in的值ok &= x
无关紧要ok
x
无论如何都会被评估,即使它的值不能产生影响。