5.2.1 使用注释的原因(2)
2. 用来说明复杂代码的注释
在实际的源代码中,好的注释同样重要。在一个处理用户输入并将结果输出到控制台的简单程序中,阅读并理解所有代码可能很容易。然而在专业领域,代码的算法经常会非常复杂或者深奥,从而很难理解。
考虑下面的代码。这段代码写得很好,但是可能无法一眼就看出其作用。如果以前见过这个算法您可能会认出它来,但是新人可能无法理解代码的运行方式。
- void sort(int inArray[], int inSize)
- {
- for (int i = 1; i < inSize; i++) {
- int element = inArray[i];
- int j = i – 1;
- while (j >= 0 && inArray[j] > element) {
- inArray[j+1] = inArray[j];
- j--;
- }
- inArray[j+1] = element;
- }
- }
较好的做法是使用注释描述所使用的算法。下面是改良后的函数,顶部的注释在较高层次说明了这个算法,行内的注释解释了可能令人疑惑的特定行。 - /*
- * Implements the "insertion sort" algorithm. The algorithm separates the
- * array into two parts--the sorted part and the unsorted part. Each
- * element, starting at position 1, is examined. Everything earlier in the
- * array is in the sorted part, so the algorithm shifts each element over
- * until the correct position is found for the current element. When the
- * algorithm finishes with the last element, the entire array is sorted.
- */
- void sort(int inArray[], int inSize)
- {
- // Start at position 1 and examine each element.
- for (int i = 1; i < inSize; i++) {
- int element = inArray[i];
- // j marks the position in the sorted part of the array.
- int j = i – 1;
- // As long as the current slot in the sorted array is higher than
- // the element, shift the slot over and move backwards.
- while (j >= 0 && inArray[j] > element) {
- inArray[j+1] = inArray[j];
- j--;
- }
- // At this point the current position in the sorted array
- // is *not* greater than the element, so this is its new position.
- inArray[j+1] = element;
- }
- }
新代码长度有所增加,但是通过注释,不熟悉排序算法的读者可能也会理解这个算法。某些组织中不赞成使用行内注释。在此类情况下,编写整洁的代码并在顶部给出函数的注释变得至关重要。