C/C++ const关键字 解读

The collocation between const and original pointer is confused to many people. There are two usages of it.
The first one is a variable pointer that points a constant data. i.e. const int* p

#include <iostream>

int main() {
	int a = 1, b = 2;
	const int *p = &a;

	p = &b;  // true
	*p = 3;  // false

	return 0;
}

The second one is a contant pointer that points a variable data. i.e. int* const p

#include <iostream>

int main() {
	int a = 1, b = 2;
	int* const p = &a;

	p = &b; // false
	*p = 3; // true

	return 0;
}

There is a good way to distinguish these two usages. You can judge them by the position of const and *.

  • If the const locates the left of the *, it means that the const keyword modifies the data *p, i.e. a constant data.
  • If the const locates the right of the *, it means that the const keyword modifies the data p, i.e. a constant pointer.

In addition, const can also collocates with C++ reference. But there is a litter difference between them.
That is because the difference between pointer and reference, which is that you can modify pointer pointing later, but you can't modify a reference pointing.
So there is no such situation that you modify the reference. You can just modify the data which is pointed by the reference.
Therefore, there is only one usage of reference, that is the const locates the left of the &. i.e. const int &p or int const &p.

posted @ 2023-09-03 16:14  0x7F  阅读(7)  评论(0编辑  收藏  举报