const与指针

const常量说明符    :定义一个常量,在程序中改变量不能被改变  

          const int a=1;  定义时必须初始化 const  int  b;   wrong

const 与 指针:

    const int * p = & i ;   int*  const p=& i ;  有什么区别呐?

       const int *p =...表示p   指向    一个常量   所以*p是不能被改变值的!

    int*  const  p = ... 表示  p  指针是一个常量 这就要求常量指针必须在声明的时候初始化了

代码:

#include <bits/stdc++.h>
using namespace std;
const int i=1;
//const 常量只能被常量指针指向,因为不能留下通过指针改变常量的漏洞
// so    int * const q=&i is wrong
int j=2;
const int *p=&i;
//(*p)++;      wrong.  a const variable can't be changed
int * const q=&j;   //

int main()
{

    (*q) ++;
    cout<<*p<<endl;       //1
    cout<<*q<<endl;       //3
    return 0;
}

  

落霞与孤鹜齐飞,秋水共长天一色
原文地址:https://www.cnblogs.com/star-and-me/p/6670301.html