在结构内部定义宏背后的逻辑是什么? [英] What is the logic behind defining macros inside a struct?

查看:136
本文介绍了在结构内部定义宏背后的逻辑是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我在质疑在结构内部定义宏的原因.我在以下片段的网络编程中经常看到这种方法:

As apparent in the title, I'm questioning the reason behind defining the macros inside a struct. I frequently see this approach in network programming for instance following snippet:

struct sniff_tcp {
    u_short th_sport;               /* source port */
    u_short th_dport;               /* destination port */
    tcp_seq th_seq;                 /* sequence number */
    tcp_seq th_ack;                 /* acknowledgement number */
    u_char  th_offx2;               /* data offset, rsvd */
#define TH_OFF(th)      (((th)->th_offx2 & 0xf0) >> 4)
    u_char  th_flags;
    #define TH_FIN  0x01
    #define TH_SYN  0x02
    #define TH_RST  0x04
    #define TH_PUSH 0x08
    #define TH_ACK  0x10
    #define TH_URG  0x20
    #define TH_ECE  0x40
    #define TH_CWR  0x80
    #define TH_FLAGS        (TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG|TH_ECE|TH_CWR)
    u_short th_win;                 /* window */
    u_short th_sum;                 /* checksum */
    u_short th_urp;                 /* urgent pointer */
};

此示例来自tcpdump网站上的 sniffex.c 代码.

This example is from sniffex.c code in tcpdump's web site.

这是为了增强可读性和使代码更清晰.

Is this for enhancing readability and making code clearer.

推荐答案

我认为这不是最佳实践",应该将(用于值的)定义保持在结构附近,而不是在结构内部.

i think, this is no "best practice", one should keep the defines (for values) near the struct, but not inside the struct.

(最好是枚举和typedef常量,因此,如果输入不正确,编译器可能会发出警告).

(Even better would be to enum and typedef the constants, so a compiler could warn if not typed properly).

另一种情况是TH_OFF()宏隐藏"了另一个元素,因此也许可以将其放在此位置(带有适当的注释)

The TH_OFF() macro is another case, where it "hides" another element, so maybe it could be put at this position (with an appropriate comment)

这篇关于在结构内部定义宏背后的逻辑是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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