C语言宏的几个注意点

  • 宏定义
    宏定义中要注意的主要有两点,一点是宏参数可能被evaluation多次。比如:
#define max(A, B) ((A) > (B) ? (A) : (B))
max(i++, j++) /* i和j中较大的值会被evaluation2次*/

当然这里宏的好处是可以不用指定A和B的类型。
另一点是宏跟括号有关的时候可能会改变evaluation的顺序。比如

#define square(x) x*x
square(z+1)
  • 条件包含
    这里面主要是关于宏的理解。
#define name replacement text

subsequent occurrences of the token name will be replaced by the replacement text. The name in a #define has the same form as a variable name; the replacement text is arbitrary. Normally the replacement text is the rest of the line, but a long definition may be continued onto several lines by placing a \ at the end of each line to be continued.

所以说一般的宏都只有一行,如果是多行的话需要用’\’去结尾。因此下面的条件包含中的宏定义只是用于条件包含,而不应该在其它地方使用。经过实验证明HDR在源文件的其它地方没有什么作用。千万不要认为将HDR定义成hdr.h的内容。

#if !defined(HDR)
#define HDR
/* contents of hdr.h go here */
#endif

或者

#ifndef HDR
#define HDR
/* contents of hdr.h go here */
#endif

The first inclusion of hdr.h defines the name HDR; subsequent inclusions will find the name defined and skip down to the #endif. A similar style can be used to avoid including files multiple times. If this style is used consistently, then each header can itself include any other headers on which it depends, without the user of the header having to deal with the interdependence.
条件包含是一个很巧妙的设计,只要每个头文件都使用条件包含,那么就可以防止重复声明变量(如果没有条件包含将变得很复杂)。

参考文献:《TLCL》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值