c - 为什么 union* 和 struct* 之间会有区别?

标签 c pointers struct language-lawyer unions

C 标准规定所有指向 union 的指针都具有相同的表示和对齐要求。
它对所有指向 struct 的指针要求相同。

因此我的问题是:
为什么标准不强制要求指向 union 的指针与指向 struct 的指针具有相同的表示和对齐要求?(我非常希望欣赏利用此实现的示例。)
还是我只是错过了相关文本?

标准草案n1570(C11最终草案)的相关引用:

6.2.5 Types § 28

A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.48) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

最佳答案

1989 ANSI C Rationale 都不是也不是 ISO C99 Rationale讨论这个。

我怀疑缺乏这样的要求是否有任何充分的理由。可能委员会不想强加不必要的严格要求。我也怀疑是否存在任何现实世界的实现,其中指向结构的指针和指向 union 的指针具有相同的表示形式。

例如,考虑一个结构可以包含单个 union 成员,反之亦然,因此可能没有充分的理由让一个实现使用不同的表示形式——标准也没有任何充分的理由要求所有实现使用相同的表示。

所有结构指针“闻起来都一样”的原因是允许使用指向不完整类型的指针。例如:

struct foo;

void func(struct foo *param);

struct foo { /* member declarations */ };

编译器不需要知道任何关于 struct foo 的信息,只要它是一个 struct 类型就可以知道如何生成对 func() 的调用

这同样适用于不完整的 union 类型。但是不完整的结构类型不能作为 union 来完成,反之亦然,因此假设它们具有相同的表示形式并没有多大好处。

关于c - 为什么 union* 和 struct* 之间会有区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24313644/

相关文章:

c - 打印 sleep \n

c - 在这个 C 程序中,第二个 scanf 被跳过,如果我使用 fflush 那么它工作正常。为什么会这样呢?

c++ - deep_const_ptr 复制构造函数

c++ - 解除引用引用

c - 如何在不使用 for 循环的情况下获取 char * 变量的大小?

ios - 动态改变API数据获取结构

c - getch() 在 C 中究竟做了什么?

C QueueLinkedList 字符串变量不起作用

c++ - 如何从另一个 .cpp 文件访问全局结构?

python - C 数组和 Python 列表之间的区别