Objective-C 邏輯運算符
下表列出了所有支持Objective-C語言的邏輯運算符。假設變量A=1,變量B=0,那麼:
運算符 | 描述 | 示例 |
---|---|---|
&& | 調用邏輯AND運算符。如果這兩個操作數不為零,則條件為真。 | (A && B) is false. |
|| | 調用邏輯或運算符。如果兩個操作數中的任何一個不為零,則條件為真。 | (A || B) is true. |
! | 調用邏輯NOT運算。使用反轉其操作數的邏輯狀態。如果一個條件是真的,那麼邏輯NOT運算符為假。 | !(A && B) is true. |
示例
嘗試下麵的例子就明白了所有在Objective-C編程語言的邏輯運算符:
#import <Foundation/Foundation.h> main() { int a = 5; int b = 20; int c ; if ( a && b ) { NSLog(@"Line 1 - Condition is true " ); } if ( a || b ) { NSLog(@"Line 2 - Condition is true " ); } /* lets change the value of a and b */ a = 0; b = 10; if ( a && b ) { NSLog(@"Line 3 - Condition is true " ); } else { NSLog(@"Line 3 - Condition is not true " ); } if ( !(a && b) ) { NSLog(@"Line 4 - Condition is true " ); } }
當編譯和執行上述程序,它會產生以下結果:
2013-09-07 22:35:57.256 demo[19012] Line 1 - Condition is true 2013-09-07 22:35:57.256 demo[19012] Line 2 - Condition is true 2013-09-07 22:35:57.256 demo[19012] Line 3 - Condition is not true 2013-09-07 22:35:57.256 demo[19012] Line 4 - Condition is true