C Typedef和结构问题 [英] C Typedef and Struct Question

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

问题描述

这两个声明有什么区别,一个优于另一个?

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.

您可以获得一些小好处:

You get a few small benefits:

  • 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 Typedef和结构问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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