c - 只将一个基本字段封装到 C 中的结构中有什么好处?

标签 c struct typedef

我看到了一些这样的 C 代码:

// A:
typedef uint32_t in_addr_t;
struct in_addr { in_addr_t s_addr; };

我总是喜欢这样:

// B:
typedef uint32_t in_addr;

所以我的问题是:在 A 和 B 中执行此操作有什么区别/好处?

最佳答案

这是一个引入类型安全的层,对“ future 的扩展”很有帮助。

前者的一个问题是,很容易将由 typedefed 内置表示的类型的值“转换”为几种其他类型或 typedefed 内置中的任何一种。

考虑:

typedef int t_millisecond;
typedef int t_second;
typedef int t_degrees;

对比:

// field notation could vary greatly here:
struct t_millisecond { int ms; };
struct t_second { int s; };
struct t_degrees { int f; };

在某些情况下,使用符号会更清晰一些,编译器也会禁止错误的转换。考虑:

int a = millsecond * second - degree;

这是一个可疑程序。使用类型定义的整数,这是一个有效的程序。使用结构时,它的格式不正确——编译器错误将需要您进行更正,并且您可以明确表达您的意图。

使用 typedef,可以应用任意算术和转换,并且可以在没有警告的情况下将它们分配给彼此,这可能成为维护的负担。

同时考虑:

t_second s = millisecond;

这也是一个致命的转变。

它只是工具箱中的另一个工具——请自行决定使用。

关于c - 只将一个基本字段封装到 C 中的结构中有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10409537/

相关文章:

c - 为什么这个 switch case 程序在整数输入之后不接受字符输入?

c - 使用递归函数打印树

c - C 中的动态字符串数组结构

c - 结构体的类型定义

被#define 和 typedef 搞糊涂了

c - gdb 堆栈溢出

c++ - 初始化两个相互引用的结构数组

c - 字节似乎被转移了

c - 打印链表数据时只打印第一个元素