您的位置:首页 > 移动开发 > Objective-C

[学习笔记—Objective-C]《Objective-C 程序设计 第6版》第六章 选择结构

2015-06-28 16:18 585 查看
跟上一章一样,本章只讲解大体的框架和相对重要的细节知识点。

Part 1. if 语句

Part1. 1 if 语句结构

if (expression1)

program statement 1;

else if (expression 2)

program statement 2;

else //也可以写成 else if (expression 3)

program statement 3;

end


注意: else 语句会和最近的无else语句的if对应。

因此,

if ( [chessGame isOver] == No)

if ([chessGame whoseTurn] == You)
[chessGame yourMove];

else
[chessGame finish];


系统会识别成:

if ( [chessGame isOver] == No)

if ([chessGame whoseTurn] == You)
[chessGame yourMove];

else
[chessGame finish];


解决办法:

if ( [chessGame isOver] == No){

if ([chessGame whoseTurn] == You)
[chessGame yourMove];
}

else
[chessGame finish];


Part 1.2 复合条件测试

if ( grade >= 70 && grade<= 79) //大于70或等于70 和 小于或等于79的时候
++grades_70_to_99


if (index<0 || index> 99) //在小于0或者大于99的时候执行NSLog
NSLoG(@"Error - index our of range");


注意:
&&
比任何关系运算符和算术运算符有更低的优先级。但是比
||
的优先级更高。

因此,在
if (( rem_4 == 0 && rem_100 != 0 ) || rem_400 == 0)
语句中,
rem_4 == 0 && rem_100 != 0
两边的括号不是必须的。

Part2. switch 语句

Part 2.1 switch语句结构

switch (expression)
{
case value 1;
program statement
break

case value 2;
program  statement
break;

default:
program statement;
break;
}


Part 2.2 switch语句:多个情况一种操作

case ‘*'
case ‘x'
case ‘X'
program statement;
break;


Part 3. 条件运算符

Part 3.1 条件运算符结构

condition? expression1 : expression2

//condition的求值结果是true(非0),则执行expression1.
//condition的求值结果是false(0),则执行expression2.


注意: 条件运算符是从右到左结合的。

因此,
e1 ? e2 : e3 ? e4 : e5
等价于
e1 ? e2 : (e3 ? e4 : e5 )
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: