设为首页 加入收藏

TOP

2.4 const Qualifier (1)
2013-10-07 15:25:13 来源: 作者: 【 】 浏览:63
Tags:2.4 const Qualifier

C++(www.cppentry.com) 中的const 有多种用途,既可以修饰变量,也可以修饰函数;并且可以和指针、引用相结合,表达更为复杂的意图。

There are two problems with the following for loop, both concerning the use of 512 as an upper bound.

  1. for (int index = 0; index != 512; ++index) {  
  2. // ...  

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:

  1. int bufSize = 512; // input buffer size  
  2. for (int index = 0; index != bufSize; ++index) {  
  3. // ...  

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:

  1. 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.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.4 const Qualifier (2) 下一篇2.2 Literal Constants (7)

评论

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

·常用meta整理 | 菜鸟 (2025-12-25 01:21:52)
·SQL HAVING 子句:深 (2025-12-25 01:21:47)
·SQL CREATE INDEX 语 (2025-12-25 01:21:45)
·Shell 传递参数 (2025-12-25 00:50:45)
·Linux echo 命令 - (2025-12-25 00:50:43)