Objective-C逻辑运算符

下表显示了Objective-C语言支持的所有逻辑运算符。 假设变量A=1,而变量B=0,则 -

运算符 描述 示例
&& 逻辑“与”运算符。 如果两个操作数都不为零,则条件成立。 (A && B)结果为:false
ΙΙ 逻辑“或”运算符。如果两个操作数中的任何一个不为零,则条件变为true (A ΙΙ B)结果为:true
! 逻辑“非”运算符。 用于反转其操作数的逻辑状态。 如果条件为true,则逻辑“非”运算符后将为false !(A && B)结果为:true

例子

尝试以下示例来了解Objective-C编程语言中可用的所有逻辑运算符 -

#import <Foundation/Foundation.h>

int main() {
   int a = 5;
   int b = 20;

   if ( a && b ) {
      NSLog(@"Line 1 - Condition is true\n" );
   }

   if ( a || b ) {
      NSLog(@"Line 2 - Condition is true\n" );
   }

   /* lets change the value of  a and b */
   a = 0;
   b = 10;

   if ( a && b ) {
      NSLog(@"Line 3 - Condition is true\n" );
   } else {
      NSLog(@"Line 3 - Condition is not true\n" );
   }

   if ( !(a && b) ) {
      NSLog(@"Line 4 - Condition is true\n" );
   }
}

执行上面示例代码,得到以下结果:

2018-11-14 05:07:48.922 main[33387] Line 1 - Condition is true
2018-11-14 05:07:48.924 main[33387] Line 2 - Condition is true
2018-11-14 05:07:48.924 main[33387] Line 3 - Condition is not true
2018-11-14 05:07:48.924 main[33387] Line 4 - Condition is true

上一篇: Objective-C运算符 下一篇: Objective-C循环