int * const and const int * difference

Outline

There are two pointers are a property, a point to where it is, it points to a place on the content. The difference is also here. What exactly const modified Yes.

Code

#include <iostream>
using namespace std;

int main()
{
	int p=1;
	int q=2;
	int k=3;
 
	const int *m=&p;
	int const *n=&q;
	int *const i=&k;
 
	//(*m)++;error C3892: “m”: 不能给常量赋值
	//(*n)++;error C3892: “n”: 不能给常量赋值
	(*i)++;
	
	cout<<"i="<<*i<<endl;
	
	m=&q;
	n=&p;
	//i=&p;error C3892: “i”: 不能给常量赋值
	cout<<"m="<<*m<<endl;
	cout<<"n="<<*n<<endl;
	
	system("pause");
    return 0;
}

in conclusion

const int with int const is the same, the content is a pointer to a constant can not be changed, a pointer to the location can be changed. And int * const contrary, point to the content can be changed with the above two, pointing to the location can not be changed.

const int * m and const int n, m, and n is a pointer to a constant, which is a modified constant const m, n, indicating that m * n can not be changed. I.e., it is a first pointer can point to many places, but once a point where, m and n are constant, i.e., the contents of which can not be changed.

And int const pointer i is constant, i.e. constant const modifier i, and i is a pointer, where i refers to not change, but where i refers to the content, i.e., i may vary.

Published 10 original articles · won praise 1 · views 491

Guess you like

Origin blog.csdn.net/qq_34681580/article/details/104804029