Objective-C嵌套if语句

在Objective-C编程中,嵌套if-else语句是合法的,可以在一个ifelse if语句中使用ifelse if语句。

语法

嵌套if语句的语法如下 -

if( boolean_expression1) {
   /* 如果 boolean_expression1 为true,则执行 */
   if(boolean_expression2) {
      /* 如果 boolean_expression2 为true,则执行 */
   }
}

可以使用与嵌套if语句类似的方式嵌套if else语句。

示例代码

#import <Foundation/Foundation.h>

int main () {

   /* 定义局部变量 */
   int a = 100;
   int b = 200;

   /* 检查布尔条件 */
   if( a == 100 ) {

      /* 如果条件为true,则继续检查以下条件 */
      if( b == 200 ) {
         /* 如果条件为true,则打印以下结果 */
         NSLog(@"Value of a is 100 and b is 200\n" );
      }
   }
   NSLog(@"Exact value of a is : %d\n", a );
   NSLog(@"Exact value of b is : %d\n", b );

   return 0;
}

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

2018-11-14 09:40:57.545 main[149996] Value of a is 100 and b is 200
2018-11-14 09:40:57.547 main[149996] Exact value of a is : 100
2018-11-14 09:40:57.547 main[149996] Exact value of b is : 200

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