首页 > 其他 > 详细

c中关于#与##的简易使用

时间:2015-01-12 12:58:31      阅读:162      评论:0      收藏:0      [点我收藏+]

#运算符用于在预编译时,将宏参数转换为字符串

eg.

#include <stdio.h>
#define CONVERT(f)(#f)

void helloworld()
{
printf("hi,tom welcome to you!");
}

int main()
{
printf("%s\n",CONVERT(hello world!));
printf("%s\n",CONVERT(100));
printf("%s\n",CONVERT(while));
printf("%s\n",CONVERT(return));
printf("%s\n",CONVERT(helloworld));
return 0;
}

输出:

技术分享

 

printf("%s\n",CONVERT(helloworld)); 这句并没有执行函数里面的内容,没有输出:printf("hi,tom welcome to you!");

CONVERT宏只是输出了函数的名称。

 

 

##运算符则用于在预编译时,粘连两个符号

一般情况下,我们是这么定义结构体的:

#include <stdio.h>

typedef struct _student
{
int id;
char* name;
}student;

int main()
{
student s1;
s1.id=1;
s1.name="tth";
printf("id:%d\n",s1.id);
printf("name:%s\n",s1.name);

student *p1;
p1=&s1;
printf("p1-id:%d\n",p1->id);
printf("p1-name:%s\n",p1->name);

return 0;
}

当有了##运算符符后,我们可以这么定义结构体:

#include <stdio.h>
#define STUDENT(type)typedef struct _##type type;\
struct _##type
STUDENT(student)
{
int id;
char *name;
};


int main()
{
student s1;
s1.id=1;
s1.name="tth";

printf("id:%d",s1.id);
printf("name:%s",s1.name);
return 0;
}

输出:

技术分享

c中关于#与##的简易使用

原文:http://www.cnblogs.com/ltlly/p/4218080.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!