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
語句測試各種條件非常有用。
當使用if
,else if
,else
語句時,要記住幾點 -
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函數