gpt4 book ai didi

C11相关语言正确性

转载 作者:太空狗 更新时间:2023-10-29 14:55:50 24 4
gpt4 key购买 nike

以下代码片段是来自 C11 standard §6.5.2.3 的示例:

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);
}

根据 C11,g() 中的最后一行无效。为什么这样?

最佳答案

示例来自 ISO/IEC 9899:2011 的§6.5.2.3 结构和 union 成员中的示例 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.

问题中引用的代码前面有注释:

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

现在,根据突出显示的声明,这是有道理的。 g() 中的代码使用了公共(public)初始序列,但这仅适用于 union 可见且在 f( )

问题也是严格别名问题之一。这是一个复杂的话题。参见 What is the strict aliasing rule?了解详情。

无论值(value)如何,即使在严格的警告选项下,GCC 7.1.0 也不会报告该问题。即使使用 -Weverything 选项,Clang 也不会:

clang -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes \
-Wstrict-prototypes -Weverything -pedantic …

关于C11相关语言正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45338651/

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