gpt4 book ai didi

c++ - 指针和 `const` 的 C/C++ 约定

转载 作者:太空宇宙 更新时间:2023-11-04 05:35:27 25 4
gpt4 key购买 nike

我已阅读 this (也粘贴在下面)在维基百科上:

Following usual C convention for declarations, declaration follows use, and the * in a pointer is written on the pointer, indicating dereferencing. For example, in the declaration int *ptr, the dereferenced form *ptr is an int, while the reference form ptr is a pointer to an int. Thus const modifies the name to its right. The C++ convention is instead to associate the * with the type, as in int* ptr, and read the const as modifying the type to the left. int const * ptrToConst can thus be read as "*ptrToConst is a int const" (the value is constant), or "ptrToConst is a int const *" (the pointer is a pointer to a constant integer).

我实在得不到满意的解释:

  • 它在什么意义上进行修改?

  • name vs type 的用途是什么(参见上面的链接)?

  • 为什么它应该在 const 的右侧?

最佳答案

constvolatilerestrict(从 C99 开始)关键字被视为类型限定符。它们是类型签名的组成部分,并描述了有关类型的附加语义。

如果它们出现在声明的最顶层,它们会影响声明的标识符:

const int a = 5; // prevents modifications of "a"
int *const p = &x; // prevents modifications of "p", but not "*p"
int **const q = &y; // prevents modifications of "q", but not "*q" and "**q"

如果它们出现在指针子类型中(在星号之前),它们会在特定的解引用级别影响指向的值:

const int *p = &x; // prevents modifications of "*p", but not "p"
const int **q = &y; // prevents modifications of "**q", but not "*q" and "q"
const int *const *r = &z; // prevents modifications of "**r" and "*r", but not "r"
const int *const *const s = &a; // prevents modifications of "**s", "*s" and "s"

维基百科摘录讨论了两种不同的指针声明约定:

int *p; // more common in C programming
int* p; // more common in C++ programming

我会说“真实”约定是第一个约定,因为它根据语言的语法(声明镜像使用)工作。该声明中的星号实际上与您在普通表达式中的指针上使用的解引用运算符相同。因此,在 p(指针本身)上应用 *(间接)后返回 int 类型。

另请注意,类型限定符相对于类型说明符和其他类型限定符的顺序无关紧要,因此这些声明是等效的:

const int a; // preferred
int const a; // same, not preferred

const volatile int b; // preferred
volatile const int b; // same, not preferred
volatile int const b; // same, not preferred

const int *p; // preferred
int const *p; // same, not preferred

关于c++ - 指针和 `const` 的 C/C++ 约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39483685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com