2.8 常量

原文来自:http://www.learncpp.com/cpp-tutorial/28-constants/

C++使用两种常量:字面常量和符号常量。

字面常量

通过展示几个例子进行说明

   1: int x = 5; // 5 is a literal constant
   1: unsigned int nValue = 5u; // unsigned constant
   2: long nValue2 = 5L; // long constant

默认情况下,浮点型字面常量是double类型的。把它们转化成float值,可以通过增加f或F的后缀。

   1: float fValue = 5.0f; // float constant

通常,避免使用不是0或1的字面常量是一个很好的想法。更详细的可以参看magic numbers一文中。

 

符号常量

可以通过#define声明一个符号变量:

   1: #define YEN_PER_DOLLAR  122
   2: int nYen = nDollars * YEN_PER_DOLLAR;

 

使用#define进行声明需要注意两个主要问题。首先,因为它们是被预处理器处理的,将符号名用defined的值取代,#defined符号常量不会再debugger中显示。或者,如果你仅仅看到语句 int nYen = nDollars * YEN_PER_DOLLAR;,你不得不寻找#define声明获取YEN_PER_DOLLAR具体使用的值。

其次,#define值通常具有全局作用域。这意味着一个片段中#defined声明的变量名可能在另一段代码中再次#defined声明。

更好的方式是使用const关键词来声明符号常量。const变量必须在声明的时候进行赋值,此后该值将不能被改变。上面的例子改编成如下方式:

   1: const int nYenPerDollar = 122;
   2: int nYen = nDollars * nYenPerDollar;

如果对const值进行改变就会出现编译错误。

   1: const int nYenPerDollar = 122;
   2: nYenPerDollar = 123; // compiler error!

 

const能够使你避免使用magic numbers,并使得你的代码更加的易读。有些程序员更倾向于使用大写字符的变量名,作为const变量的名称。const变量的用法除了不能更改外与其他变量的用法相同。

posted @ 2012-05-07 17:20  grassofsky  阅读(316)  评论(0编辑  收藏  举报