Duanxx的C++学习: const指针具体解释

本文详细介绍了C++中const关键字的用途及其在指针中的应用方式,并解释了为什么在嵌入式程序中使用const的重要性。通过示例代码帮助读者理解const如何限制变量和指针的修改。

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

         keywordconst使得代码能够确定一个变量能否够被改动。

使用了const后,能够防止对变量或者指针的改动;更重要的是,const的引用能够防止对所引用的对象的改动

 

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

 

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

 

关于Const的指针的使用,文字讲解没有意义,直接參见以下的代码及凝视:

#include <iostream>
// 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; ///<the data and the pointer are both const

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值