Objective-C if...else语句

if语句后面可以跟一个可选的else语句,else语句在布尔表达式为false时执行。

语法

Objective-C编程语言中if...else语句的语法是 -

if(boolean_expression) {
   /* statement(s) 如果布尔表达式为true,则执行此语句 */
} else {
  /* statement(s) 如果布尔表达式为false,则执行此语句 */
}

如果布尔表达式(boolean_expression)的计算结果为true,那么将执行if代码块,否则将执行else中的代码块。

Objective-C编程语言将任何非零和非null值假定为true,如果它为零或null,则将其假定为false

流程图

示例代码

#import <Foundation/Foundation.h>

int main () {
   /* 局部变量定义 */
   int a = 100;

   /* 检查布尔条件 */
   if( a < 20 ) {
      /* 如果条件为true,则打印以下结果 */
      NSLog(@"a is less than 20\n" );
   } else {
      /* 如果条件为false,则打印以下结果 */
      NSLog(@"a is not less than 20\n" );
   }

   NSLog(@"value of a is : %d\n", a);
   return 0;
}

编译并执行上述代码时,会产生以下结果 -

2018-11-14 09:23:05.241 main[6546] a is not less than 20
2018-11-14 09:23:05.243 main[6546] value of a is : 100

if…else if…else语句

if语句后面可以跟一个可选的else if...else语句,这对于使用单个if...else if语句测试各种条件非常有用。

当使用ifelse ifelse语句时,要记住几点 -

  • if可以有零个或一个else,它必须在else if之后。
  • if可以有零或多个else if,并且它们必须在else之前。
  • 当有一个else if条件匹配成功,其余的else if或者else都不会再条件匹配测试。

语法

Objective-C编程语言中if...else if语句的语法是 -

if(boolean_expression 1) {
   /* Executes when the boolean expression 1 is true */
} else if( boolean_expression 2) {
   /* Executes when the boolean expression 2 is true */
} else if( boolean_expression 3) {
   /* Executes when the boolean expression 3 is true */
} else {
   /* executes when the none of the above condition is true */
}

示例代码

#import <Foundation/Foundation.h>

int main () {
   /* 定义局部变量 */
   int a = 100;

   /* 检查布尔条件 */
   if( a == 10 ) {
      /* 如果if条件为真,则打印以下内容 */
      NSLog(@"Value of a is 10\n" );
   } else if( a == 20 ) {
      /* 如果else...if条件为真,则打印以下内容 */
      NSLog(@"Value of a is 20\n" );
   } else if( a == 30 ) {
      /* 如果else...if条件为真,则打印以下内容 */
      NSLog(@"Value of a is 30\n" );
   } else {
      /* 如果没有一个条件为真,则打印以下内容 */
      NSLog(@"None of the values is matching\n" );
   }
   NSLog(@"Exact value of a is: %d\n", a );
   return 0;
}

编译并执行上述代码时,会产生以下结果 -

2018-11-14 09:31:07.594 main[96166] None of the values is matching
2018-11-14 09:31:07.596 main[96166] Exact value of a is: 100

上一篇: Objective-C决策 下一篇: Objective-C函数