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

跟上一章一样,本章只讲解大体的框架和相对重要的细节知识点。

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 )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值