Duanxx的C++学习: const指针详解

2015-07-20 17:28:56 · 作者: · 浏览: 4

Const指的是一个编译时的常量。

关键字const使得代码可以确定一个变量是否可以被修改。

使用了const后,可以防止对变量或者指针的修改;更重要的是,const的引用可以防止对所引用的对象的修改。

一般来说,在C语言中,对于一些常量的定义,我习惯性的使用define,而在C++中则最好改为使用const。

对于嵌入式程序而言,const的使用则是相当的微妙的,被const修饰后,其变量是存放在ROM中的,这一点很重要。

关于Const的指针的使用,文字解说没有意义,直接参见下面的代码及注释:

#include 
  
   
// const
// - a compile time constraint that an object can not be modified

int main()
{
	const int i = 1;
	int a = 0;
	const int *p1 = &i;		///< data is const ,but pointer is not

	int* const p2 = &a;	    ///< pointer p2 itself is const ,but the data p2 point to is not const
	//int* const p3 = &i;     ///< illegal , cannot convert from 'const int *' to 'int *const '
	int const* p4 = p1;      ///< if const is on the left of *,data is const
						///< if cosnt is on the right of *,pointer is const

	const int* const p5 = &i; ///