Objective-C if...else 语句
if 语句后面可以通过一个可选的else语句,布尔表达式为假时执行。
语法:
在Objective-C编程语言的if... else语句的语法是:
if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ }
如果布尔表达式的值为true,那么将要执行的if block代码块,else block 代码块将被执行。
Objective-C语言的编程语言假设为真,任何非零和非空值,如果它是零或者为null,那么它被假定为false。
流程图:
例如:
#import <Foundation/Foundation.h> int main () { /* local variable definition */ int a = 100; /* check the boolean condition */ if( a < 20 ) { /* if condition is true then print the following */ NSLog(@"a is less than 20 " ); } else { /* if condition is false then print the following */ NSLog(@"a is not less than 20 " ); } NSLog(@"value of a is : %d ", a); return 0; }
上面的代码编译和执行时,它会产生以下结果:
2013-09-07 22:04:10.199 demo[3537] a is not less than 20 2013-09-07 22:04:10.200 demo[3537] value of a is : 100
if...else if...else 语句
if语句后面可以跟一个可选的 else if...else 语句,这是非常有用的,如果使用单... else if语句来测试各种条件。
当使用 if , else if , else 语句时,有几点要牢记:
-
一个if可以有零个或一个else,它必须跟在else if之后。
-
一个if 可以有零或许多else if,他们必须出现在else之前。
-
else if 一旦成功,否则,剩余的else if'将不会被测试执行。
语法:
if...else if...else 语句语法在Objective-C编程语言是:
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 () { /* local variable definition */ int a = 100; /* check the boolean condition */ if( a == 10 ) { /* if condition is true then print the following */ NSLog(@"Value of a is 10 " ); } else if( a == 20 ) { /* if else if condition is true */ NSLog(@"Value of a is 20 " ); } else if( a == 30 ) { /* if else if condition is true */ NSLog(@"Value of a is 30 " ); } else { /* if none of the conditions is true */ NSLog(@"None of the values is matching " ); } NSLog(@"Exact value of a is: %d ", a ); return 0; }
上面的代码编译和执行时,它会产生以下结果:
2013-09-07 22:05:34.168 demo[8465] None of the values is matching 2013-09-07 22:05:34.168 demo[8465] Exact value of a is: 100