首页 > 学院 > 开发设计 > 正文

第二章 变量和基本类型——2.4 const 限定符

2019-11-08 01:05:32
字体:
来源:转载
供稿:网友

编写程序的时候,有时我们需要定义一些常量,比如512大小的缓冲区,我们可以用数字512来表示;也可以定义变量int bufSize = 512等等。

前者不利于程序的可读性,同时维护性差,被称为魔数(magic number)

后者虽然通过定义变量解决了上述两种问题,但其仍可被修改,所以并不能保证绝对的安全

2.4.1. 定义const对象


const int bufSize = 512; //input buffer sizebufSize = 0; //error: attempt to write to const objectconst int i, j = 0; //error: i is uninitialized const

const对象定义以后不能被修改

const对象定义时必须初始化

2.4.2. const对象默认为文件的局部变量


在全局作用域里定义const变量,他在整个程序中都可访问,只要在其他文件中进行extern声明即可。

//file_1.cppint couter; //definition in file_1.cpp//file_2.cppextern 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 filesextern const int bufSize = 512; //file_2.cppextern const int bufSize;for (int index = 0; index != bufSize; ++index)//...

Tips:

const变量默认为extern。要是const变量能够在其他文件中被访问,需要显示的指定它为extern


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表