使用const修饰指针

指针传递给函数有四种方式

1:指向非常量数据的非常量指针(int *p)

2:指向常量数据的非常量指针    (const int *p)

3:指向非常量数据的常量指针    (int *const p)

4:指向常量数据的常量指针     (const int*const ptr)

 

1:指向非常量数据的非常量指针(int *p)

可以通过指针间接修改数据。

可以修改指针指向其他数据。

#include
using namespace std;
int main()
{  int x=5,y=8;
    //可以通过指针间接修改数据,操作1.

    int*p=&x;
    *p=7;
    cout<

2:指向常量数据的非常量指针    (const int *p)

不能通过修改指针来修改其指向的数据。

可以用其为函数接收实参,函数可以操作但不能修改数据。

#include
using namespace std;
void f(const int *p)
{
    cout<<*p+*p;
}
//错误写法
//void(const int *p)
//{*p=100;}

int main()
{

int y=9;
f(&y);
return 0;
}

 

3:指向非常量数据的常量指针    (int *const p)

     始终指针始终内存中同一位置,通过该指针可修改这个位置的数据。

#include
using namespace std;
int main()
{
int x=2,y=3;
int *const p=&x;
//错误写法
//错误int *const p; *p=&x;(初始化要直接赋值)
//错误*p=y;(只能指向同一位置,指向x后不能变)
*p=5;
cout<

4:指向常量数据的常量指针     (const int*const ptr)

只能指向内存中同一位置,且这个位置的值不能变。

#include
using namespace std;
int main()
{
int x=2;
const int *const p=&x;
//*p=5;错误
cout<

 

你可能感兴趣的:(使用const修饰指针)