c语言中#define进行多行宏定义 应用
首先我用例子说明,这样能快速的理解。如果利用c语言想打印一长串的信息,往往我们会这么写:
printf("hanshanbuleng: 年龄 %d 工作 %s 学校 %s",age,work,college);
但是利用#define进行多行宏定义,我们就可以进行简化了,如下所示:
#define HSBL \
"hanshanbuleng age%d "\
"work%s " \
"college%s!\n"\
此时我们利用hanshanbuleng来替换原始方式:
同过以下方式实现:printf(HSBL, "20+", "秘密", "秘密");
我们的屏幕就会出现:hanshanbuleng age20+ work秘密 college秘密!
值得我们注意的是:这时候注释加入就需要改变
e.g.
#define HSBL \
"hanshanbuleng age%d " \
"work%s "\
"college%s!\n" //年龄 \ 这样加就不会出错
e.g.
#define HSBL \
"hanshanbuleng age%d " \
"work%s "\
"college%s!\n"\ //年龄 出错哦
以下给出一个复杂的define多行定义 其方法也是如上相同。
#define TYPEDEF_LIST(t) \
LIST_NODE(t) { \
LIST_NODE(t) *prev; \
LIST_NODE(t) *next; \
t data; \
}; \
typedef struct { \
LIST_NODE(t) *head; \
LIST_NODE(t) *free; \
int len; \
int nodeCount; \
int nodeSize; \
}
在此我给出了整体程序调试,自己也可以动手试试呀
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#define HSBL \"hanshanbuleng age%s " \
"work%s " \
"college%s!\n" \
#define LIST_NODE(t) struct _list_node_##t
#define TYPEDEF_LIST(t) \
LIST_NODE(t) { \
LIST_NODE(t) *prev; \
LIST_NODE(t) *next; \
}; \
typedef struct { \
LIST_NODE(t) *head; \
LIST_NODE(t) *free; \
int len; \
int nodeCount; \
int nodeSize; \
}
int main()
{
LIST_NODE(int)* HSBL_Node = NULL;
int ret = 0;
//system("pause");
printf(HSBL, "20+", "秘密", "秘密");
return ret;
}