Objective-C 關係運算符
下表列出了所有支持Objective-C語言的關係運算符。假設變量A=10和變量B=20,則:
運算符 | 描述 | 示例 |
---|---|---|
== | 檢查是否兩個操作數的值等於或不等於,如果是的話那麼條件為真。 | (A == B) is not true. |
!= | 檢查兩個操作數的值等於或不相等,如果值不相等,則條件為真。 | (A != B) is true. |
> | 檢查是否左操作數的值大於右操作數的值,如果是的話那麼條件為真。 | (A > B) is not true. |
< | 檢查是否左操作數的值小於右操作數的值,如果是的話那麼條件為真。 | (A < B) is true. |
>= | 檢查是否左操作數的值大於或等於右操作數的值,如果是的話那麼條件為真。 | (A >= B) is not true. |
<= | 檢查是否左操作數的值小於或等於右邊的操作數的值,如果是的話那麼條件為真。 | (A <= B) is true. |
例子
嘗試下麵的例子就明白了在Objective-C編程語言的所有關係運算符:
#import <Foundation/Foundation.h> main() { int a = 21; int b = 10; int c ; if( a == b ) { NSLog(@"Line 1 - a is equal to b " ); } else { NSLog(@"Line 1 - a is not equal to b " ); } if ( a < b ) { NSLog(@"Line 2 - a is less than b " ); } else { NSLog(@"Line 2 - a is not less than b " ); } if ( a > b ) { NSLog(@"Line 3 - a is greater than b " ); } else { NSLog(@"Line 3 - a is not greater than b " ); } /* Lets change value of a and b */ a = 5; b = 20; if ( a <= b ) { NSLog(@"Line 4 - a is either less than or equal to b " ); } if ( b >= a ) { NSLog(@"Line 5 - b is either greater than or equal to b " ); } }
當編譯和執行上述程序,它會產生以下結果:
2013-09-07 22:42:18.254 demo[9486] Line 1 - a is not equal to b 2013-09-07 22:42:18.254 demo[9486] Line 2 - a is not less than b 2013-09-07 22:42:18.254 demo[9486] Line 3 - a is greater than b 2013-09-07 22:42:18.254 demo[9486] Line 4 - a is either less than or equal to b 2013-09-07 22:42:18.254 demo[9486] Line 5 - b is either greater than or equal to b