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 @   0x7F  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示