如标题所示,我质疑在结构中定义宏的原因。我经常在网络编程中看到这种方法,例如以下片段:
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 */
};
这个例子来自 sniffex.c tcpdump 网站中的代码。
这是为了增强可读性,让代码更清晰。
最佳答案
好吧,定义的常量与其中一个字段的可能值相关。
因此,作者决定改进代码的局部性,让API用户避免原地踏步。似乎合乎逻辑。
否则,预处理器完全独立于代码。您甚至可以将定义放在表达式中。
关于c - 在结构中定义宏背后的逻辑是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3051893/