预处理器
预处理器是一些指令,指示编译器在实际编译之前所需完成的预处理。
所有的预处理器指令都是以井号(#)开头,只有空格字符可以出现在预处理指令之前。预处理指令不是 C++ 语句,所以它们不会以分号(;)结尾。
我们已经看到,之前所有的实例中都有 #include 指令。这个宏用于把头文件包含到源文件中。
C++ 还支持很多预处理指令,比如 #include、#define、#if、#else、#line 等,让我们一起看看这些重要指令。
#define 预处理
#define 预处理指令用于创建符号常量。该符号常量通常称为宏,指令的一般形式是:
#define macro-name replacement-textCode language: CSS (css)
当这一行代码出现在一个文件中时,在该文件中后续出现的所有宏都将会在程序编译之前被替换为 replacement-text。例如:
#include <iostream>
#include <string>
using namespace std;
#define PI 3.1415926
int main()
{
cout << PI << endl;
double d = PI;
cout << PI * 2 * 2 << endl;
return 0;
}Code language: PHP (php)
您可以使用 #define 来定义一个带有参数的宏,如下所示:
#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;
//上面语句最后会在编译之前被替换为
cout << "较小的值为:" << (i < j ? i : j) << endl;
return 0;
}Code language: PHP (php)
当上面的代码被编译和执行时,它会产生下列结果:
较小的值为:30
条件编译
有几个指令可以用来有选择地对部分程序源代码进行编译。这个过程被称为条件编译。
条件预处理器的结构与 if 选择结构很像。请看下面这段预处理器的代码:
#ifdef NULL
#define NULL 0
#endifCode language: CSS (css)
您可以只在调试时进行编译,调试开关可以使用一个宏来实现,如下所示:
#ifdef DEBUG
cerr <<"Variable x = " << x << endl;
#endifCode language: PHP (php)
如果在指令 #ifdef DEBUG 之前已经定义了符号常量 DEBUG,则会对程序中的 cerr 语句进行编译。您可以使用 #if 0 语句注释掉程序的一部分,如下所示:
#if 0
不进行编译的代码
#endifCode language: CSS (css)
让我们尝试下面的实例:
#include <iostream>
using namespace std;
#define DEBUG
int main()
{
int x = 12;
#ifdef DEBUG
cerr << "Variable x = " << x << endl;
#endif
}Code language: PHP (php)
当上面的代码被编译和执行时,它会产生下列结果:
Variable x = 12
这些 #define DEBUG 通常在调试的时候用到,正式发布的时候就会被过滤,很适合调试代码。
# 和 ## 运算符
# 和 ## 预处理运算符在 C++ 和 ANSI/ISO C 中都是可用的。
# 运算符会把 replacement-text 令牌转换为用引号引起来的字符串。
请看下面的宏定义:
#include <iostream>
using namespace std;
#define MKSTR( x ) #x
int main ()
{
cout << MKSTR(HELLO C++) << endl;
return 0;
}Code language: PHP (php)
当上面的代码被编译和执行时,它会产生下列结果:
HELLO C++
让我们来看看它是如何工作的。不难理解,C++ 预处理器把下面这行:
cout << MKSTR(HELLO C++) << endl;
转换成了:
cout << "HELLO C++" << endl;Code language: JavaScript (javascript)
## 运算符用于连接两个令牌。下面是一个实例:
#define CONCAT( x, y ) x ## yCode language: CSS (css)
当 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;
}Code language: PHP (php)
当上面的代码被编译和执行时,它会产生下列结果:
100
让我们来看看它是如何工作的。不难理解,C++ 预处理器把下面这行:
cout << concat(x, y);
转换成了:
cout << xy;