设为首页 加入收藏

TOP

5.2.1 使用注释的原因(2)
2013-10-07 15:34:54 来源: 作者: 【 】 浏览:67
Tags:5.2.1 使用 注释 原因

5.2.1  使用注释的原因(2)

2. 用来说明复杂代码的注释

在实际的源代码中,好的注释同样重要。在一个处理用户输入并将结果输出到控制台的简单程序中,阅读并理解所有代码可能很容易。然而在专业领域,代码的算法经常会非常复杂或者深奥,从而很难理解。

考虑下面的代码。这段代码写得很好,但是可能无法一眼就看出其作用。如果以前见过这个算法您可能会认出它来,但是新人可能无法理解代码的运行方式。

  1. void sort(int inArray[], int inSize)  
  2. {  
  3. for (int i = 1; i < inSize; i++) {  
  4. int element = inArray[i];  
  5. int j = i – 1;  
  6. while (j >= 0 && inArray[j] > element) {  
  7. inArray[j+1] = inArray[j];  
  8. j--;  
  9. }  
  10. inArray[j+1] = element;  
  11. }  
  12. }  

较好的做法是使用注释描述所使用的算法。下面是改良后的函数,顶部的注释在较高层次说明了这个算法,行内的注释解释了可能令人疑惑的特定行。
  1. /*  
  2. * Implements the "insertion sort" algorithm. The algorithm separates the  
  3. * array into two parts--the sorted part and the unsorted part. Each  
  4. * element, starting at position 1, is examined. Everything earlier in the  
  5. * array is in the sorted part, so the algorithm shifts each element over  
  6. * until the correct position is found for the current element. When the  
  7. * algorithm finishes with the last element, the entire array is sorted.  
  8. */  
  9. void sort(int inArray[], int inSize)  
  10. {  
  11. // Start at position 1 and examine each element.  
  12. for (int i = 1; i < inSize; i++) {  
  13. int element = inArray[i];  
  14. // j marks the position in the sorted part of the array.  
  15. int j = i – 1;  
  16. // As long as the current slot in the sorted array is higher than  
  17. // the element, shift the slot over and move backwards.  
  18. while (j >= 0 && inArray[j] > element) {  
  19. inArray[j+1] = inArray[j];  
  20. j--;  
  21. }  
  22. // At this point the current position in the sorted array  
  23. // is *not* greater than the element, so this is its new position.  
  24. inArray[j+1] = element;  
  25. }  
  26. }  

新代码长度有所增加,但是通过注释,不熟悉排序算法的读者可能也会理解这个算法。某些组织中不赞成使用行内注释。在此类情况下,编写整洁的代码并在顶部给出函数的注释变得至关重要。
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇5.2.1 使用注释的原因(3) 下一篇5.2.1 使用注释的原因(1)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·哈希表 - 菜鸟教程 (2025-12-24 20:18:55)
·MySQL存储引擎InnoDB (2025-12-24 20:18:53)
·索引堆及其优化 - 菜 (2025-12-24 20:18:50)
·Shell 中各种括号的 (2025-12-24 19:50:39)
·Shell 变量 - 菜鸟教 (2025-12-24 19:50:37)