当前位置:网站首页>c 语言中宏参数的字符串化跟宏参数的连接
c 语言中宏参数的字符串化跟宏参数的连接
2022-07-26 10:43:00 【aLLLiyyy】
c语言中的宏有无参数的宏,也有带参数的宏。
其实宏就相当与一个字符串模板,然后预处理器在有宏的标志处,把宏展开,说明白点,也就是字符串的替换工作。不过这个工作发生在编译之前,以前一直不理解,感觉c语言中的宏有多高大上,原来只是对你的c代码进行一些字符串的替换工作,替换后,还是c语言,然后才开始编译成汇编等指令。
现在说说如何定义一个有参数的宏,比如最简单的宏定义
#define MAX(a,b) (a)>(b)?(a):(b)
这样,当我们在代码中遇见MAX()的标志时候,预编译处理器(注意不是编译器)会自动替换这个模板,然后展开就相当与比较两个数字的大小;
如下所示:
int getMax(int x,int y) {
return MAX(x, y);
}
表面上看起来引用了一个宏,其实经过预处理器进行字符串的替换工作,然后就变成这样了:
int getMax(int x,int y) {
return (x)>(y)?(x):(y);
}
看到了没有,宏只是替换字符串,再简单不过了,就是不知道为什么其他语言没有宏这个概念。
明白了宏的概念,那么。我们进对宏的参数做两个操作,宏参数字符串化,宏参数的连接。
1.红参数的字符串化,如下:
#define STR(a) #a
通过#这个字符,就可以把宏里面的参数 a给变成字符串,举例如下
cout << STR(hello everyone!) << endl;
这样,就可以打印出 hello everyone!这个字符串!
2.宏参数的简单连接。
#define JOIN(a,b) a##b
这样就简单 的把 a,b两个变量的内容做了一个字符串的拼接操作,如下代码会输出1234.
cout << JOIN(12,34) << endl;
注意,只是简单的字符串连接。没有任何加减乘除的操作。
边栏推荐
猜你喜欢
![[notes on machine learning] [building a cyclic neural network and its application] deeplearning ai course5 1st week programming(keras)](/img/02/f85da2a2f2524fb034b17ed8d06692.png)
[notes on machine learning] [building a cyclic neural network and its application] deeplearning ai course5 1st week programming(keras)

按二进制数中1的个数分类

RT-Thread 学习笔记(三)---用SCons 构建编译环境

putty的使用教程

Oracle cannot start tnslistener service cannot start

349. 两个数组的交集
![[machine learning notes] [style transfer] deeplearning ai course4 4th week programming(tensorflow2)](/img/94/ff52b043320b6dea5ca1238e314de8.png)
[machine learning notes] [style transfer] deeplearning ai course4 4th week programming(tensorflow2)
![[paper after dinner] deep mining external perfect data for chestx ray disease screening](/img/d6/41c75d292c26b2e7e116767a51eb5e.png)
[paper after dinner] deep mining external perfect data for chestx ray disease screening

粽子大战 —— 猜猜谁能赢

RT-Thread 学习笔记(六)--- 开启基于SPI Flash的elmfat文件系统(上)
随机推荐
oracle 启动不了 tnslistener服务启动不了
Constructors, method overloads, object arrays, and static
1748.唯一元素的和
.net operation redis set unordered collection
RT-Thread 学习笔记(七)---开启基于SPI Flash的elmfat文件系统(中)
关于硕博士开题报告编写的思考
27.移除元素
Flutter 防止科学计数并去除尾数无效0
鹏哥C语言第七节课总结
剑指Offer(五十三):表示数值的字符串
鹏哥C语言第四课(3)
Flutter jni混淆 引入.so文件release包闪退
px2rem-loader将px转化为rem,适配移动端vant-UI等框架
The problem of formatting IAR sprintf floating point to 0.0 in UCOS assembly
Error[Pe147]: declaration is incompatible with '错误问题
display-inline+calc实现左中右布局,中间自适应
对面向抽象编程的理解
智能合约dapp系统开发流程技术
剑指Offer(四十四):翻转单词顺序序列
2021-08-14三子棋