AnA*_*ons 2 c struct typedef language-lawyer
I'm wondering if you declare a structure like this:
typedef struct
{
//...
} name;
Run Code Online (Sandbox Code Playgroud)
Then is it the case that every subsequent declaration of type 'name' will have distinct type?
I'm wondering this because of (from standard) $6.7.2.3(p5):
Two declarations of structure, union, or enumerated types which are in different scopes or use different tags declare distinct types. Each declaration of a structure, union, or enumerated type which does not include a tag declares a distinct type.
And this $6.7.8(p3):
In a declaration whose storage-class specifier is typedef, each declarator defines an identifier to be a typedef name that denotes the type specified for the identifier in the way described in 6.7.6.
And so something like this would be illegal (although clang will accept it):
typedef struct{
int a, b;
} s;
void func(s);
int main()
{
s a = {2, 2};
s b = a;
}
Run Code Online (Sandbox Code Playgroud)
If it is not the case please explain why?
Each declaration of a structure, union, or enumerated type which does not include a tag declares a distinct type.
这一行是说每次你声明这样一个 type,那都是一个新类型。这并不是说每次你声明一个这样类型的变量时,你就声明了一个新类型。
您的代码只声明一次类型,因此它只创建一种类型。
我想你误会了
结构、联合或枚举类型的每个声明
这是一个结构类型的声明:
struct s1 {
int a, b;
};
Run Code Online (Sandbox Code Playgroud)
这也是
typedef struct {
int a, b;
} s2;
Run Code Online (Sandbox Code Playgroud)
它也是 typedef 的声明。这是结构类型和对象的声明:
struct {
int a, b;
} o1;
Run Code Online (Sandbox Code Playgroud)
这不是结构类型的声明:
s2 o4, o5;
Run Code Online (Sandbox Code Playgroud)
它是两个对象的声明,每个对象都有结构类型。但是这里没有声明结构类型。
该标准特别指出
struct-or-union-speci?er 中存在的struct-declaration-list声明了翻译单元内的新类型。
这种结构声明列表是括号内的一切。
所以这也不是结构类型的声明:
struct s1 o2, o3;
Run Code Online (Sandbox Code Playgroud)
同样,它声明对象,并为它们提供结构类型,但由于缺少struct-declaration-list,它不声明类型。