首页 技术 正文
技术 2022年11月6日
0 收藏 999 点赞 997 浏览 1481 个字

直接上代码

1.#define 预处理

#include <iostream>
using namespace std;#define PI 3.14159int main ()
{ cout << "Value of PI :" << PI << endl; return 0;
}

2.参数宏

#include <iostream>
using namespace std;#define MIN(a,b) (a<b ? a : b)int main ()
{
int i, j;
i = 100;
j = 30;
cout <<"较小的值为:" << MIN(i, j) << endl; return 0;
}

3.条件编译

有几个指令可以用来有选择地对部分程序源代码进行编译。这个过程被称为条件编译。

条件预处理器的结构与 if 选择结构很像。请看下面这段预处理器的代码:

#ifndef NULL
#define NULL 0
#endif

您可以只在调试时进行编译,调试开关可以使用一个宏来实现,如下所示:

#ifdef DEBUG
cerr <<"Variable x = " << x << endl;
#endif

如果在指令 #ifdef DEBUG 之前已经定义了符号常量 DEBUG,则会对程序中的 cerr 语句进行编译。您可以使用 #if 0 语句注释掉程序的一部分,如下所示:

#if 0
不进行编译的代码
#endif
#include <iostream>
using namespace std;
#define DEBUG#define MIN(a,b) (((a)<(b)) ? a : b)int main ()
{
int i, j;
i = 100;
j = 30;
#ifdef DEBUG
cerr <<"Trace: Inside main function" << endl;
#endif#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;
}

运行结果是

C++ 预处理器

4.# 和 ## 运算符

# 和 ## 预处理运算符在 C++ 和 ANSI/ISO C 中都是可用的。# 运算符会把 replacement-text 令牌转换为用引号引起来的字符串。

请看下面的宏定义:

#include <iostream>
using namespace std;#define MKSTR( x ) #xint main ()
{
cout << MKSTR(HELLO C++) << endl; return 0;
}

当上面的代码被编译和执行时,它会产生下列结果:

C++ 预处理器

让我们来看看它是如何工作的。不难理解,C++ 预处理器把下面这行:

cout << MKSTR(HELLO C++) << endl;

转换成了:

cout << "HELLO C++" << endl;

## 运算符用于连接两个令牌。下面是一个实例:

#define CONCAT( x, y )  x ## y

当 CONCAT 出现在程序中时,它的参数会被连接起来,并用来取代宏。例如,程序中 CONCAT(HELLO, C++) 会被替换为 “HELLO C++”,如下面实例所示。

#include <iostream>
using namespace std;#define concat(a, b) a ## b
int main()
{
int xy = 100; cout << concat(x, y);
return 0;
}

当上面的代码被编译和执行时,它会产生下列结果:

C++ 预处理器

让我们来看看它是如何工作的。不难理解,C++ 预处理器把下面这行:

C++ 预处理器

转换成了:

C++ 预处理器

5.C++ 中的预定义宏

C++ 提供了下表所示的一些预定义宏:

C++ 预处理器

让我们看看上述这些宏的实例:

C++ 预处理器

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,556
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898