c - C语言中,结构,定义上的细微差别

标签 c tags structure definition

我在下面看到了定义结构的格式

typedef struct Tag 
{
  type Member1;
  type Member2;
  <and so on..>
};

有些地方我看到了下面定义结构体的格式

typedef struct Tag 
{
  type Member1;
  type Member2;
  <and so on..>
} Tag;

有些地方我看到了下面定义结构的格式

typedef struct 
{
  type Member1;
  type Member2;
  <and so on..>
} Tag;

如果您注意到 Tag 语法在 struct 之后,也在右大括号处。

问题。

1) 3者有什么区别?

2) 一个比另一个更受青睐吗?或者什么时候您可能希望使用其中一个的最佳条件?

最佳答案

根据C标准(6.2.3标识符的命名空间)

1 If more than one declaration of a particular identifier is visible at any point in a translation unit, the syntactic context disambiguates uses that refer to different entities. Thus, there are separate name spaces for various categories of identifiers, as follows:

— label names (disambiguated by the syntax of the label declaration and use);

— the tags of structures, unions, and enumerations (disambiguated by following any32) of the keywords struct, union, or enum);

— the members of structures or unions; each structure or union has a separate name space for its members (disambiguated by the type of the expression used to access the member via the . or -> operator);

— all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).

这是

struct Tag 
{
  type Tag;
  <and so on..>
};

一个名为Tag的结构声明,同时它也是一个结构定义,因为它不仅引入了类型struct Tag,而且还声明了它的成员。

您可以先声明一个结构,然后定义它。例如

#include <stdio.h>

struct Tag;

struct Tag
{
    int Tag;
};

int main(void) 
{
    struct Tag Tag = { .Tag = 10 };

    printf( "Tag.Tag = %d\n", Tag.Tag );

    return 0;
}

程序输出为

Tag.Tag = 10

在这个声明中

struct Tag 
{
  type Tag;
  <and so on..>
} Tag;

声明了一个类型为 struct Tag 的对象,标识符为 Tag。该结构有一个名为 Tag 的数据成员。因此声明了两个实体:一个类型 struct Tag 和一个名为 Tag 的结构类型的对象。

在这个声明中

struct 
{
  type Tag;
  <and so on..>
} Tag;

声明了一个未命名结构类型的对象,标识符为Tag。这个声明的问题是你不能引用对象的类型。

你可以再遇到一个这样的声明

typedef struct Tag 
{
  type Tag;
  <and so on..>
} Tag;

在此 typedef 声明中,标识符 Tag 用作类型 struct Tag 的别名。

或者

typedef struct  
{
  type Tag;
  <and so on..>
} Tag;

在此 typedef 声明中,标识符 Tag 用作未命名结构类型的别名。

C 2011 允许声明匿名结构。 来自 C 标准(6.7.2.1 结构和 union 说明符)

13 An unnamed member of structure type with no tag is called an anonymous structure; an unnamed member of union type with no tag is called an anonymous union. The members of an anonymous structure or union are considered to be members of the containing structure or union. This applies recursively if the containing structure or union is also anonymous.

关于c - C语言中,结构,定义上的细微差别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44420835/

相关文章:

C++比较结构数组中的字符串

c - 对十进制输入进行二进制运算

html - self 关闭的 HTML/XML 标签的正确术语是什么?

c - 显示链接列表时出现运行时错误的原因可能是什么

git: checkout 一个标签,修改一些东西,然后再次标记它

php - 打开/关闭标签和性能?

C 共享内存在结构体中传递结构体

c - c中的结构来存储员工的详细信息并打印那些超过10000的员工

python - 在 Python 中删除一个对象和对它的所有引用?

c++ - 降低时间复杂度