第十七章,不常见的控制结构
前言
谨慎的使用这些控制结构,将会获得更多的帮助。
17.1 子程序中有多处返回
<!-- [if !supportLists]-->1、 <!-- [endif]-->如果能够增强可读性,那么就是用 return 。
<!-- [if !supportLists]-->2、 <!-- [endif]-->用防卫子句来简化复杂的错误处理。
<!-- [if !supportLists]-->3、 <!-- [endif]-->减少子程序中 return 的数量。
17.2 递归
使用递归的技巧:
<!-- [if !supportLists]-->1、 <!-- [endif]-->确认递归能够停止。
<!-- [if !supportLists]-->2、 <!-- [endif]-->使用安全计数器防止出现无穷递归。
<!-- [if !supportLists]-->3、 <!-- [endif]-->把递归限制在一个子程序中。
<!-- [if !supportLists]-->4、 <!-- [endif]-->留心栈空间。
<!-- [if !supportLists]-->5、 <!-- [endif]-->不要用递归计算阶乘和斐波那契数列。
17.2 goto
CHECKLIST: Unusual Control Structures核对表:不常见的控制结构Return <!-- [if !supportLists]-->1、 <!-- [endif]-->每一个子程序都仅在必要的时候才使用 return 吗? <!-- [if !supportLists]-->2、 <!-- [endif]-->使用 return 有助于增强可读性吗? 递归 <!-- [if !supportLists]-->1、 <!-- [endif]-->递归子程序包含了停止递归的代码了吗? <!-- [if !supportLists]-->2、 <!-- [endif]-->子程序使用安全计数器来确保该子程序能够挺下来吗? <!-- [if !supportLists]-->3、 <!-- [endif]-->递归只位于一个子程序中吗? <!-- [if !supportLists]-->4、 <!-- [endif]-->子程序的递归深度处于程序栈容量可以满足的限度吗? <!-- [if !supportLists]-->5、 <!-- [endif]-->递归是实现子程序的最佳方法吗? Goto |
本章要点
多个 return 可以提高子程序的可读性,同时避免产生很深的嵌套逻辑。