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 datap
, 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
.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具