c++ - 理解 "const"在声明中的位置

标签 c++ c syntax constants

我在为 C 和 C++ 语言的声明中使用 const 的方式找到直观的模式时遇到了麻烦。以下是一些示例:

const int a;    //Const integer
int const a;    //Const integer
const int * a;  //Pointer to constant integer
int * const a;  //Const pointer to an integer
int const * a const;    //Const pointer to a const integer

在第 1 行和第 2 行中,似乎 const 可以出现在 int 之前或之后,这是它所修改的。

  1. 那么,在第 4 行,编译器如何确定 const 正在修改 *(指针)而不是 int
  2. 编译器遵循什么规则来决定 const 适用于哪个事物?
  3. * 是否遵循相同的规则?

最佳答案

假设你总是把 const 放在类型的 right 上,你可以从右到左把变量声明读成一句话:

int const x;        // x is a constant int
int *const x;       // x is a constant pointer to an int
int const *x;       // x is a pointer to a constant int
int const *const x; // x is a constant pointer to a constant int

如果您将 const 放在类型的左侧,这仍然有效,但需要更多的脑力劳动。请注意,这同样适用于指向指针的指针(和更高阶的结构):

int *const *const x; // x is a constant pointer to a constant pointer to an int

关于c++ - 理解 "const"在声明中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6590820/

相关文章:

c++ - 是否可以更改类成员缓冲区的大小

c++ - 在 C++ 中使用 THIS 指针将对象写入文件

c++ - 将用户输入限制为某些字符

php - 这个 PHP MySQL 查询有什么问题?

syntax - 正确需要嵌套 IIF 或 SWITCH 语句语法

c++ - c++项目需要通过kinect进行语音识别的dll

c# - 导入的 C 函数在 C# 中有效,但在 VB6 中无效

c - `errno`的语义

c++ - 并行计算——混淆了输出?

参数中的 jQuery、Colorbox、jQuery 语法