gpt4 book ai didi

澄清 C11 标准中的 union 示例

转载 作者:太空狗 更新时间:2023-10-29 16:47:39 24 4
gpt4 key购买 nike

C11标准6.5.2.3中给出了下面的例子

The following is not a valid fragment (because the union type is not visible within function f):

struct t1 { int m; };
struct t2 { int m; };
int f(struct t1 *p1, struct t2 *p2)
{
if (p1->m < 0)
p2->m = -p2->m;
return p1->m;
}
int g()
{
union {
struct t1 s1;
struct t2 s2;
} u;
/* ... */
return f(&u.s1, &u.s2);
}

为什么 union 类型对函数 f 可见很重要?

在阅读相关部分几遍时,我在包含部分中没有看到任何不允许这样做的内容。

最佳答案

这很重要,因为 6.5.2.3 第 6 段(强调已添加):

One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the completed type of the union is visible. Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.

这不是需要诊断的错误(语法错误或违反约束),但行为未定义,因为 struct t1m 成员>struct t2 对象占用相同的存储空间,但是因为 struct t1struct t2 是不同的类型,所以允许编译器假设它们不——特别是对 p1->m 的更改不会影响 p2->m 的值。例如,编译器可以在第一次访问时将 p1->m 的值保存在寄存器中,然后在第二次访问时不从内存中重新加载它。

关于澄清 C11 标准中的 union 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36192191/

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