【发布时间】:2018-03-25 18:37:18
【问题描述】:
这是一个多部分的问题。
我一直在尝试理解 C 类型系统。首先是C标准 经常提到“兼容类型”这个词,所以我试图理解这一点。 定义似乎很分散,但根据我的发现:
6.2.7 兼容类型和复合类型 1 两种类型如果它们的类型相同,则它们具有兼容类型。确定的附加规则 6.7.2 中描述了两种类型是否兼容 说明符,在 6.7.3 中用于类型限定符,在 6.7.6 中用于 declarators.55) 此外,两种结构、联合或枚举类型 如果它们的标签在单独的翻译单元中声明是兼容的 并且成员满足以下要求:如果一个被声明 一个标签,另一个应该用相同的标签声明。如果两者都是 在各自翻译单元内的任何地方完成,然后 以下附加要求适用:应有一对一 他们的成员之间的对应关系,使得每一对 相应的成员被声明为兼容的类型;如果一个 该对的成员使用对齐说明符声明,另一个 用等效的对齐说明符声明;如果一个成员 一对用名称声明,另一个用 一样的名字。对于两个结构,应声明相应的成员 以相同的顺序。对于两个结构或联合,对应 位域应具有相同的宽度。对于两个枚举, 相应的成员应具有相同的值。
REFS:
6.7.2 short == short int == signed short == signed short int, etc.
6.7.3
10) For two qualified types to be compatible, both shall have the identically qualified version of a compatible type; the order of type qualifiers within a list of specifiers or qualifiers does not affect the specified type.
6.7.6
1.2)
For two pointer types to be compatible, both shall be identically qualified and both shall be pointers to compatible types.
2.6)
For two array types to be compatible, both shall have compatible element types, and if both size specifiers are present, and are integer constant expressions, then both size specifiers shall have the same constant value. If the two array types are used in a context which requires them to be compatible, it is undefined behavior if the two size specifiers evaluate to unequal values.
在我看来
- 如果它们的所有完整部分相同,则这两种类型是兼容的。
- (由于 1.)“完全兼容类型”实际上意味着“相同类型”。
首先,我想问一下我的解释是否准确。
其次,标准中的_Generic 选择是根据“兼容类型”的概念定义的:
6.5.1.1 类属选择 2 类属选择应具有不超过一个默认类属关联。泛型中的类型名称 关联应指定一个完整的对象类型,而不是一个变量 修改型。同一个泛型中没有两个泛型关联 选择应指定兼容的类型。控制表达式 泛型选择的类型应与最多一个兼容的类型 在其通用关联列表中命名的类型。如果一个泛型 选择没有默认的通用关联,它的控制 表达式应具有与其中一种类型完全兼容的类型 在其通用关联列表中命名。
但编译器似乎对顶级限定符有不同的解释:
$ $CC -x c -include stdio.h - <<<'int main(){puts( _Generic((int const){0}, int:"int", int const: "int const")); }' && ./a.out #int with gcc, and int const with clang
在我看来,铿锵的解释是正确的,但令人困惑的是
$ $CC -x c -include stdio.h - <<<'int main(){puts( _Generic((int const)0, int:"int", int const: "int const")); }' && ./a.out
说"int" 甚至在叮当声。
所以我的第二个问题是,将(int const)0 解释为int 类型和(int const){0} 类型为int const 的标准的基础是什么?
最后,在我的所有编译器(tcc、gcc、clang)中,原型类型列表中的所有类型似乎都忽略了顶级限定符 在确定函数或函数指针之间的兼容性时:
for CC in tcc gcc clang; do echo CC=$CC; $CC -x c - <<<'int main(){ static void (*f)(int*), (*g)(int * restrict const volatile); f=g; }' ; done #no complaints
但我在标准中找不到任何提及,所以我的最后一个问题是:
在确定功能兼容性的上下文中,忽略原型类型列表中类型的顶级限定符是否符合标准?
谢谢。
【问题讨论】:
-
而接受的答案是错误的:D
标签: c generics language-lawyer type-systems