美文网首页C/C++
初学C中的const时遇到的一些疑惑和解决

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

作者: Dumbass | 来源:发表于2017-07-08 22:33 被阅读0次

这里说的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的产生,所以是不允许的。

相关文章

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

    这里说的Const 是 C 中的Qualifier 偷懒到今天才开始学习(准确地说是昨天),刚把多维数组的指针搞明...

  • 初学C语言

    初学C语言——if语句 #includeint main(int argc,const char * argv[]...

  • 初学C语言

    初学C语言——for循环语句的嵌套 #includeint main(int argc,const char * ...

  • 初学C语言

    初学C语言——if else语句 #includeint main(int argc,const char * a...

  • 初学C语言

    初学C语言——switch开关语句 #includeint main(int argc,const char * ...

  • 初学C语言

    初学C语言——利用for求和3003 #includeint main(int argc,const char *...

  • 初学C语言

    初学C语言——for循环语句 #includeint main(int argc,const char * arg...

  • 初学C语言

    初学C语言——while循环 #includeint main(int argc,const char * arg...

  • 初学C语言

    初学C语言——if-else if-else语句 #includeint main(int argc,const ...

  • C和C++中的const

    author: 冰小苏打 const 必须初始化 const 作用 1.修饰变量,说明该变量值不可以被改变2.修饰...

网友评论

    本文标题:初学C中的const时遇到的一些疑惑和解决

    本文链接:https://www.haomeiwen.com/subject/lqpjhxtx.html