C语言中#符合的作用介绍

1、宏定义中使用#符号,宏定义中使用#代表把参数变成一个字符串,宏定义中使用##代表把两个宏参数连接在一起。

具体用法:

#include<stdio.h>


#defineSTR(s) #s

#defineCONS(a, b) a##e##b


voidmain()

{

printf(STR(Hello)); => printf(“Hello”);

printf(“%d”,CONS(2,3)); => printf(“%d”, 2e3);

}


2、当宏参数是另一个宏的时候,需要注意,凡是宏定义里面用到#或者##的地方,宏参数不会再展开。

#include<stdio.h>


#defineINT_MAX 100

#defineSTR(s) #s

#defineA (2)

#defineCONS(a, b) a##e##b


voidmain()

{

printf(“%d”,STR(INT_MAX)); => printf(“%d”, “INT_MAX”);

printf(“%d”,CONS(A, A)); => printf(“%d”, AeA);

}


解决这个问题的方法很简单,中间加上一层转换即可。

#define_STR(s) STR(s)

printf(“%d”,_STR(INT_MAX)); => printf(“%d”, STR(100));


#define_CONS(a, b) CONS(a, b)

printf(“%d”,_CONS(A, A)); => printf(“%d”, CONS((2), (2)));


3###的特殊应用

#define_A1(type, var, line) type var##line

#define_A0(type, line) _A1(type, _anonymous,line)

#defineA(type) _A0(type, __LINE__)


A(staticint) => _A0(static int, _anonymous, __LINE__) => _A1(staticint, _anonymous,70) => static int _anonymous70


C语言中的__LINE__用以指示本行语句在源文件中的位置信息,举例如下:

  1. #include<stdio.h>




  2. main()

  3. {

  4. printf("%d\n",__LINE__);

  5. printf("%d\n",__LINE__);

  6. printf("%d\n",__LINE__);

  7. };

该程序在linuxgcc编译,在windowsvc6.0下编译都可以通过,执行结果都为:

7

8

9


还可以通过语句#line来重新设定__LINE__的值,举例如下:

  1. #include<stdio.h>



  2. #line200  

  3. main()

  4. {

  5. printf("%d\n",__LINE__);

  6. printf("%d\n",__LINE__);

  7. printf("%d\n",__LINE__);

  8. };

编译执行后输出结果为:

202

203

204


C语言中的__FILE__用以指示本行语句所在源文件的文件名,举例如下(test.c):

  1. #include<stdio.h>

  2. intmain()

  3. {

  4. printf("%s\n",__FILE__);

  5. }

gcc编译生成a.out,执行后输出结果为:

test.c

windowsvc6.0下编译执行结果为:

c:\documentsand settings\administrator\桌面\test.c


另外gcc还支持__func__,它指示所在的函数,但是这个关键字不被windows下的vc6.0支持.

  1. #include<stdio.h>

  2. voidmain()

  3. {

  4. printf("thisis print by function %s\n",__func__);

  5. }

其编译后输出结果为

thisis print by function main


#defineFILL(a) {a, #a}

enumIDD{OPEN, CLOSE};


typedefstruct MSG

{

IDDid;

constchar *msg;

}MSG;


MSG_msg[] = {FILL(OPEN), FILL(CLOSE)};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值