变量声明问题

发布于 2024-10-11 21:18:26 字数 137 浏览 6 评论 0原文

解释变量 p 和 q 的声明方式之间的差异。描述何时使用一种声明以及何时使用另一种声明。

int x = 5;

const int *p = &x;

int * const q = &x;

Explain the difference between how variables p and q are declared. Describe when you would use one declaration and when you would use the other.

int x = 5;

const int *p = &x;

int * const q = &x;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

残疾 2024-10-18 21:18:26
int x = 5;
const int *p = &x;

这会将x的地址分配给指向const intp的指针。这意味着 p 指向的东西是 const,不能通过取消引用 p 来写入。

int * const q = &x;

这会将x的地址分配给指向int的const指针q。这意味着,指针是常量,之后无法更改,但是您可以通过取消引用 p 来更改 x

int x = 5;
const int *p = &x;

This assigns the address of x to the pointer to const int p. That means the thing p points to is const and cannot be written to by de-referencing p.

int * const q = &x;

This assigns the address of x to the const pointer to int q. That means, the pointer is const and cannot be altered afterwards, you can however alter x by de-referencing p.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文