c - typedef 指针常量怪异

标签 c constants typedef

请考虑以下代码:

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

const PersonRef person = NULL;

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

出于某种原因,编译器提示只读值不可分配。但是const关键字不应该使指针成为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/52303477/

相关文章:

c - 如何获取lua脚本的执行百分比?

c++ - 强制类的 const 成员在编译时进行评估

c++ - typedef 类的前向声明

c - 通过函数传递结构时收到警告

c - 二维数组中的总线错误

c - C free() 是如何工作的?

c - sqrt 仅在参数为非负时定义

c++ - 为什么在第二类中使用 static const 会在第一类中产生编译器错误?

c++ - 我应该对 C++ 中的非顺序常量使用枚举还是多个常量?

c# - 在 C# 中输入别名