C 类型定义和结构问题 [英] C Typedef and Struct Question

查看:18
本文介绍了C 类型定义和结构问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个声明之间有什么区别,哪个比另一个更受欢迎?

What's the difference between these two declarations, and is one preferred over the other?

typedef struct IOPORT {  
    GPIO_TypeDef* port;  
    u16           pin;  
} IOPORT;  

typedef struct {  
    GPIO_TypeDef* port;  
    u16           pin;  
} IOPORT;  

推荐答案

至于哪种风格更受欢迎,我更喜欢第一种风格(在结构标记中和作为结构的 typedef 中的名称)仅仅是因为有除了源文件中的几个字符外,没有任何缺点.我的 IDE 的结构片段在两个地方都删除了名称,所以我总是得到一个 typedef 的结构名称和一个结构标记名称.

As far as which style is preferred, I prefer the 1st style (with the name in both the struct tag and as a typedef for the struct) simply because there are no drawbacks other than a few more characters in the source file. My IDE's struct snippet drops the name in both places, so I always get a typedef'ed struct name along with a struct tag name.

你会得到一些小好处:

  • struct STRUCTNAME"可用于在结构体中声明指向结构体的指针
  • 只需在 C 或 C++ 代码中使用 STRUCTNAME 就可以逃脱
  • 您可以防止 C++ 中潜在的(即使在实践中非常罕见)与用于另一个对象的结构名称有关的奇怪现象,而不会出现错误或警告
  • the "struct STRUCTNAME" can be used to declare pointers to the struct within the struct
  • you can get away with just using STRUCTNAME in either C or C++ code
  • you prevent a potential (even if very rare in practice) oddity in C++ having to do with the struct name being used for another object without error or warning

但是,如果我碰巧手动输入结构体定义,我经常会懒惰地忽略声明一个或另一个名称.

But, if I happen to manually type in the struct definition, I'll often lazily neglect declaring one or the other name.

这篇关于C 类型定义和结构问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆