初学C中的const时遇到的一些疑惑和解决

这里说的Const 是 C 中的Qualifier

偷懒到今天才开始学习(准确地说是昨天),刚把多维数组的指针搞明白一些,就遇到了新问题。
先来看看到目前为止我懂了些什么:

#include <stdio.h>
int main(void)
{
  int n = 1;
  int junk;
  int *p = &n;
  const int * cptr = &n; // cptr is supposed to protect the data it refers to,which,in this case,is the value of n.
  *cptr = 0; //When you try to change the value of 'n',the complier shall warn you.This statement is illegal.
  n = 0; //But you can still change the value of 'n',as long as you don't use 'cptr' to change its value.
  int * const pptr = &n; //The const qualifier can also be used to protect the value of a pointer.For example,we use const to protect the value of pptr.
  pptr = &junk; //Since the pptr is protected,this statement is illegal.
  return 0;
}

上文的程序是我到目前为止已经明白的东西,都已经用注释清楚地写在旁边了。
然而,当const涉及间接运算(非一层运算)时,我就,彻底,傻了!
考虑下面的代码:

const int ** pp1;
int * p1;
pp1 = &p1; //illegal.

为什么这样的操作是不允许的呢?
我们用之前对const的理解来试着解释这个问题,pp1是指向指针的指针,而const这一qualifier要求pp1指向的指针指向的数据是不能通过pp1来改变的。
而如果我们允许上述操作,下面的操作就成为可能:

int * p1;
const int ** pp1;
const int n = 10;
pp1 = &p1; //Assume that it's legal.
*pp1 = &n; // p1 now refers to const int n.
*p1 = 1; //Changed the value of const int n.

综上所述,这样子的间接运算容易导致const失去效果,导致bug的产生,所以是不允许的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 前言 把《C++ Primer》[https://book.douban.com/subject/25708312...
    尤汐Yogy阅读 13,159评论 1 51
  • 重新系统学习下C++;但是还是少了好多知识点;socket;unix;stl;boost等; C++ 教程 | 菜...
    kakukeme阅读 20,310评论 0 50
  • 基本内置类型 算术类型字符整型布尔值浮点数 空类型(void) 算术类型 带符号类型和无符号类型int、short...
    2625K阅读 8,799评论 0 1
  • 阿喵很怕和赵大作家一起看电视剧。因为赵大作家总是问阿喵一些阿喵不知道的问题,例如: 赵大作家:他俩是不是姊妹俩吧?...
    小阿喵啊阅读 1,396评论 0 1
  • 《雪 》 这是个适合写雪的季节,因为雪已经真实的来了,于是关于雪的文字铺天盖地而来。可我总感觉这些雪很浮躁、狂乱,...
    妤梦人生阅读 1,661评论 0 8

友情链接更多精彩内容