|
C++(www.cppentry.com) 中的const 有多种用途,既可以修饰变量,也可以修饰函数;并且可以和指针、引用相结合,表达更为复杂的意图。
There are two problems with the following for loop, both concerning the use of 512 as an upper bound. - for (int index = 0; index != 512; ++index) {
-
}
The first problem is readability. What does it mean to compare index with 512 What is the loop doing—that is, what makes 512 matter (In this example, 512 is known as a magic number, one whose significance is not evident within the context of its use. It is as if the number had been plucked by magic from thin air.)
The second problem is maintainability. Imagine that we have a large program in which the number 512 occurs 100 times. Let’s further assume that 80 of these references use 512 to indicate the size of a particular buffer but the other 20 use 512 for different purposes. Now we discover that we need to increase the buffer size to 1024. To make this change, we must examine every one of the places that the number 512 appears. Wemust determine—correctly in every case—which of those uses of 512 refer to the buffer size and which do not. Getting even one instance wrong breaks the program and requires us to go back and reexamine each use.
The solution to both problems is to use an object initialized to 512: - int bufSize = 512;
- for (int index = 0; index != bufSize; ++index) {
-
- }
By choosing a mnemonic name, such as bufSize, we make the program more readable. The test is now against the object rather than the literal constant: - index != bufSize
If we need to change this size, the 80 occurrences no longer need to be found and corrected. Rather, only the one line that initializes bufSize requires change. Not only does this approach require significantly less work, but also the likelihood of making a mistake is greatly reduced.
|