c - typedef 指针常量怪异

标签 c constants typedef

请考虑以下代码:

typedef struct Person* PersonRef;
struct Person {
  int age;
};

const PersonRef person = NULL;

void changePerson(PersonRef newPerson) {
  person = newPerson;
}

出于某种原因,编译器提示只读值不可分配。但是 const 关键字不应该使指针成为常量。有什么想法吗?

最佳答案

注意

typedef int* intptr;
const intptr x;

不同于:

const int* x;

intptr 是指向 int 的指针。 const intptr 是指向int 的常量指针,而不是指向常量int 的指针。

so, after a typedef pointer, i can't make it const to the content anymore?

还有一些丑陋的方式,比如gcc的typeof macro :

typedef int* intptr;
intptr dummy;
const typeof(*dummy) *x;

但是,如您所见,如果您知道 intptr 背后的类型是没有意义的。

关于c - typedef 指针常量怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8504411/

相关文章:

c++ - 如何确定 C++ 对象是否为 time_t

c - 使用带有指针的 typedef const 结构

c - 理解 C 中的 gets() 函数

c - 编译器在转换整型常量时做什么?

c++ - 是否可以为const操作指定一个private成员变量public?

c - 为什么在 C 的头文件中使用 typedef struct?

用native c win32编写的循环缓冲区

c - 使用 OpenMP block 来破坏缓存

c - mex:计算权;但是,我得到了错误的输出

c++ - 为什么在运行时而不是在编译时使用 constexpr 初始化变量