c - 在创建 typedef 结构时指定两种类型有什么好处?

标签 c struct coding-style typedef c11

示例 1:

struct T{
    int a;
};

创建类型struct T


示例 2:

typedef struct {
    int a;
} T;

创建类型T


示例 3:

typedef struct T{
    int a;
} T;

创建类型 struct TT


我经常看到示例 3,我不确定为什么有人会选择它而不是示例 1 或 2。

  • 这样做对您有什么好处吗?
  • 人们这样做是为了兼容性吗?
  • 出于某种范围界定原因,它是否有利?

我想避免使用示例 3 的方式,因为它对类型的维护较少,并且它限制了声明同一事物的多种方式。但是,如果这种“双重命名”技术有好处,我会重新考虑。

最佳答案

I tend to see example 3 a lot, and I'm not sure why someone would choose it over example 1 or 2.

  • Are there any advantages you gain from doing it this way?

我认为这个道理是不言而喻的,繁琐的代码就是繁琐的。每个人都愿意写

T object;

代替

struct T object;

但是,硬核 C 程序员可能会认为嘿,T 是一个结构,最好这样调用它 而且,它减少了您混淆的机会' d 在做的时候得到

struct {int a; } T; typedef int T; 
  • Are there reasons people do this for compatibility?

是的。这样,C 中的结构可以像在 C++ 中一样使用。

  • Is it advantageous for some kind of scoping reason?

不,我不知道。

关于c - 在创建 typedef 结构时指定两种类型有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29550576/

相关文章:

检查功能不起作用

c++ - 链表数组大小不同

Javascript : Coding standards, Pascal 大小写还是 Camel 大小写?

c - [C] : When a pointer to a pointer to a struct is passed in a function, 为什么它不能更改该结构的元素?

coding-style - 谓词函数的最佳命名方式是什么?

javascript - 编写优雅的 JavaScript 而不是 if-then 分支

c - 为什么有些人在调用 malloc 后不检查 NULL?

c++ - 使用 C 或 C++ 制作自定义运行对话框?

c - 减少 C 代码量

c - 空的初始值设定项列表是有效的 C 代码吗?