#define预处理
#includeusing namespace std; #define PI 3.14159 //define将后面所有出现的PI 定义为3.14159 int main () { cout << "Value of PI :" << PI << endl; return 0; }
#参数宏
#includeusing namespace std; #define MIN(a,b) (a #条件编译:有选择对源代码进行编译
#includeusing 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; } #和##运算符
# 运算符会把 replacement-text 令牌转换为用引号引起来的字符串。
#includeusing namespace std; #define MKSTR( x ) #x int main () { cout << MKSTR(HELLO C++) << endl; return 0; } ## 运算符用于连接两个令牌。
#includeusing namespace std; #define concat(a, b) a ## b int main() { int xy = 100; cout << concat(x, y); return 0; } #C++中预定义宏
#includeusing 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; }



