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函數