打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C语言#和##操作符使用方法

https://blog.csdn.net/liuchunjie11/article/details/80558877

一、总结

       1、#操作符

              1:#操作符用于预处理阶段,将宏参数转换为字符串,只有宏定义中使用(#define)

                    使用方法:

                    #define  STRING(x)   #x

                   printf("%s\n",STRING(Hello World!));

        2、##操作符

              1:##操作符用于预处理阶段,将粘连两个标识符,只有宏定义中使用(#define)

                   使用方法:

                   #define  CONNECT(a,b)   a##b

                   int  CONNECT(a,1);    //int a1

                   a1 = 2;

二、代码测试

            想一个问题啊,怎样打印任意函数名出来?

  1. #include <stdio.h>
  2. #define STRING(x) #x
  3. //下面这个宏就是实现打印认识函数名称方法
  4. #define CALL(f,p) (printf("Call function %s\n",#f),f(p))
  5. int square(int n)
  6. {
  7. return n*n;
  8. }
  9. int func(int n)
  10. {
  11. return n;
  12. }
  13. #define NAME(n) name##n
  14. //传统方式:
  15. //typedef struct _tag_Student Student;
  16. //struct _tag_Student
  17. //{
  18. // char* name;
  19. // int id;
  20. //};
  21. //用宏定义方式
  22. #define STRUCT(type) typedef struct _tag_##type type;\
  23. struct _tag_##type
  24. STRUCT(Student)
  25. {
  26. char* name;
  27. int id;
  28. };
  29. int main()
  30. {
  31. int result = 0;
  32. int NAME(1); //定义name1
  33. int NAME(2); //定义name2
  34. Student s1;
  35. Student s2;
  36. //************演示#运算符使用方法*************//
  37. printf("%s\n",STRING(Hello World));
  38. printf("%s\n",STRING(100));
  39. printf("%s\n",STRING(while));
  40. printf("%s\n\n",STRING(return));
  41. //************演示#打印任意函数名称方法********//
  42. result = CALL(square,4);
  43. printf("result = %d\n",result);
  44. result = CALL(func,10);
  45. printf("result = %d\n\n",result);
  46. //************演示##运算符使用方法************//
  47. NAME(1) = 1; //name1 = 1
  48. NAME(2) = 2; //name2 = 2
  49. printf("%d\n",NAME(1)); //打印name1 = 1
  50. printf("%d\n",NAME(2)); //打印name2 = 2
  51. //************演示##定义结构体特殊用法*********//
  52. s1.name = "Lilei";
  53. s1.id = 0;
  54. printf("s1.name = %s s1.id = %d\n",s1.name,s1.id);
  55. s2.name = "Hanmeimei";
  56. s2.id = 1;
  57. printf("s2.name = %s s2.id = %d\n",s2.name,s2.id);
  58. return 0;
  59. }

程序比较简单,都有注释

参考资料《狄泰软件C语言进阶》

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
第十八讲 struct
结构体
go语言
c语言例题
C语言指针的长度和类型深入分析
C语言中结构体详解
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服