Day 1--c语言的预处理

本文详细介绍了C++预处理器的使用,包括#define定义常量、参数宏、条件编译以及#和##运算符的应用。通过实例展示了如何利用这些特性来增强代码的功能和灵活性,例如定义宏来简化代码、实现条件编译以控制代码块的执行,以及如何使用#将标识符转换为字符串和##连接令牌。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

预处理器是一些指令,指示编译器在实际编译之前所需完成的预处理

#define预处理

#include <iostream>
using namespace std;
#define PI 3.14159
//define将后面所有出现的PI 定义为3.14159
int main ()
{
    cout << "Value of PI :" << PI << endl; 
    return 0;
}

#参数宏

#include <iostream>
using namespace std;
 
#define MIN(a,b) (a<b ? a : b)
//MIN(a,b)参数完成取a,b间的小值
int main ()
{
   int i, j;
   i = 100;
   j = 30;
   cout <<"较小的值为:" << MIN(i, j) << endl;
 
    return 0;
}
//执行结果:较小的值为:30

#条件编译:有选择对源代码进行编译

#include <iostream>
using namespace std;
#define DEBUG
#define MIN(a,b) (((a)<(b)) ? a : b)
int main ()
{
   int i, j;
   i = 100;
   j = 30;
    
//DEBUG在上面已经定义过了,该语句可以执行 
//#ifndef 表示相反
#ifdef DEBUG
   cerr <<"Trace: Inside main function" << endl;
#endif
​
//0表示的地方该语句将不会被执行  
#if 0
   cout << MKSTR(HELLO C++) << endl;
#endif
 
    
    
    
   cout <<"The minimum is " << MIN(i, j) << endl;
​
    
    
#ifdef DEBUG
   cerr <<"Trace: Coming out of main function" << endl;
#endif
    return 0;
}
​
/*执行结果:
Trace: Inside main function
The minimum is 30
Trace: Coming out of main function*/

#和##运算符

# 运算符会把 replacement-text 令牌转换为用引号引起来的字符串。

#include <iostream>
using namespace std;
 
#define MKSTR( x ) #x
 
int main ()
{
    cout << MKSTR(HELLO C++) << endl;
 
    return 0;
}
​
/*运行结果为:HELLO C++
将cout << MKSTR(HELLO C++) << endl;转化为cout << "HELLO C++" << endl;*/

## 运算符用于连接两个令牌。

#include <iostream>
using namespace std;
 
#define concat(a, b) a ## b
int main()
{
   int xy = 100;
   
   cout << concat(x, y);
   return 0;
}
​
/*运行结果:100
将 cout << concat(x, y);转化为cout << xy;*/

#C++中预定义宏

#include <iostream>
using namespace std;
 
int main ()
{
    //这会在程序编译时包含当前行号。
    cout << "Value of __LINE__ : " << __LINE__ << endl;
    //这会在程序编译时包含当前文件名。
    cout << "Value of __FILE__ : " << __FILE__ << endl;
    //这会包含一个形式为 month/day/year 的字符串,它表示把源文件转换为目标代码的日期
    cout << "Value of __DATE__ : " << __DATE__ << endl;
    //这会包含一个形式为 hour:minute:second 的字符串,它表示程序被编译的时间。
    cout << "Value of __TIME__ : " << __TIME__ << endl;
 
    return 0;
}
​
/*运行结果:
Value of __LINE__ : 6
Value of __FILE__ : test.cpp
Value of __DATE__ : Feb 28 2011
Value of __TIME__ : 18:52:48
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值