限定符const

以前对qualifier const的理解有很大的误区。
在 c专家编程中是这样描述的:
Const Isn't
The keyword const doesn't turn a variable into a constant! A symbol with the const
qualifier merely means that the symbol cannot be used for assignment. This makes the value
read -onl y through that symbol; it does not prevent the value from being modified through
some other means internal (or even external) to the program. It is pretty much useful only
for qualifying a pointer parameter, to indicate that this function will not change the data that
argument points to, but other functions may. This is perhaps the most common use of
const in C and C++.

关键字const并不能将一个变量转换成一个常量。一个带const限定符的符号仅仅是表示这个符号不能用于赋值。也就是说这个符号的值是只读的;const限定符不能阻止程序通过内部或者外部方法来修改这个值。const限定符最有用之处仅仅是限定实参指针,表示这个函数将不会改变实参指针指向的数据,但其他的函数可能会。这可能实const限定符在c和c++中最普遍的用法。

1:const限定符用在数据上。
   const int a = 1;
   表示a是只读的。

2:用在指针上。
  •    cosnt int *p;
   const限定符限定的是p指向的内容。
   p指向一个只读的整形变量,不可以通过*p来改变其值。p本身是个变量。
  •    int const *p; 与上面的是等价的。  
  •    int * const p = &variable;
   const限定符限定的是p,p的值是只读的。

  •    const int *cosnt p = &variable;
   第一个const限定符限定的是p指向的内容,不可以通过*p来改变其值。
   第二个const限定符限定的是p, p的值是只读的。
  
const和*的组合通常只用于模拟数组形式参数的按值传递,它声明:我给你一个指向它的指针,但你不可以改变它。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值