编写程序的时候,有时我们需要定义一些常量,比如512
大小的缓冲区,我们可以用数字512
来表示;也可以定义变量int bufSize = 512
等等。
前者不利于程序的可读性,同时维护性差,被称为魔数(magic number)
后者虽然通过定义变量解决了上述两种问题,但其仍可被修改,所以并不能保证绝对的安全
2.4.1. 定义const
对象
const int bufSize = 512; //input buffer size
bufSize = 0; //error: attempt to write to const object
const int i, j = 0; //error: i is uninitialized const
const
对象定义以后不能被修改const
对象定义时必须初始化
2.4.2. const
对象默认为文件的局部变量
在全局作用域里定义非
const
变量,他在整个程序中都可访问,只要在其他文件中进行extern
声明即可。//file_1.cpp int couter; //definition in file_1.cpp //file_2.cpp extern int couter; //declaration in file_2.cpp ++couter; //utilization in file_2.cpp
除非做了特殊的
extern
声明,在全局作用域中定义const
变量是定义该对象文件的局部变量,其他文件中并不能够访问。想要从其他文件中进行访问,必须要在定义时显示表明该const
变量是extern
的。//file_1.cpp //extern is necessary for the const accessible to other files extern const int bufSize = 512; //file_2.cpp extern const int bufSize; for (int index = 0; index != bufSize; ++index) //...
Tips:
非const
变量默认为extern
。要是const
变量能够在其他文件中被访问,需要显示的指定它为extern