Objective-C if...else語句

2019-10-16 23:15:13

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