1. C语言build-in的宏:__FILE__,__func__,__FUNCTION__,__LINE__,__TIME__,__DATE__
2. 编译器特定的扩展的宏:__linux__,__i386__
3.自定义常用的宏
自定义的宏注意事项:参数必须要(),因为参数有可能为表达式,保证运算的优先级 ;
多语句必须用do{} while(0),且while(0)后不能加分号;
多语句换行必须在后面加上"\";
单语句要加()
(1)Swap()宏的实现,用于交换两个变量的值
#define SWAP(x, y) do{\
(x) = (x) + (y);\
(y) = (x) - (y);\
(x) = (x) - (y);\
} while(0)
#define SWAP(x, y) do{\
(x) = (x) ^ (y);\
(y) = (x) ^ (y);\
(x) = (x) ^ (y);\
} while(0)
#define SWAP(x, y) do{\
typeof(x) tmp;\
tmp = (x);\
(x) = (y);\
(y) = tmp;\
} while(0)
(2)max()和min()宏的实现,求两值比较,求最大最小值
#define max(x, y) ((x) > (y) ? (x) : (y))
#define min(x, y) ((x) < (y) ? (x) : (y))
(3)Container_of的宏实现,已知结构体某个成员的地址,求该结构体变量的地址
#define container_of(ptr, type, member) \
(type *)((char *)ptr - (long)(&((type *)0)->member))
(4)求数组成员的个数
#define ARRAY_ELEM_NUM(arr) (sizeof(arr) / sizeof((arr)[0]))
(5)字节和KB,MB,GB的转换
#define KB(n) ((n) << 10)
#define MB(n) ((n) << 20)
#define GB(n) ((n) << 30)
(6)NULL的定义
#define NULL ((void *)0)