首页 > 技术文章 > C++ 宏的使用

lucy-lizhi 2017-06-03 14:22 原文

宏的使用完整代码如下:

macrodemo.h文件:

 1 #pragma once
 2 #ifndef __MACRODEMO__
 3 #define __MACRODEMO__
 4 #include <iostream>
 5 #include <bitset>
 6 using namespace std;
 7 #define __DEBUG__    //(5)
 8 #define MAX 1000     //(1)
 9 #define MAX_FUN(a,b) ((a)<(b)?(b):(a))    //(2)
10 #define SHOW_CODE_LOCATION() cout << __FILE__ <<":" << __LINE__ << '\n'   //(3)
11 
12 #define TEST(bitmap,n) (\
13 bitmap[n]\
14 )
15 
16 #define SWAP_INT(a,b) do\        //(4)
17 {\
18 int temp = a;\
19 a = b;\
20 b = temp;\
21 }while(0)
22 
23 #endif // !__MACRODEMO__

 cpp代码如下:

 1 // MacroDemo.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include "macrodemo.h"
 7 using namespace std;
 8 
 9 int main()
10 {    
11     cout << MAX << endl;
12 #ifdef __DEBUG__
13     cout << "debug opened:" << endl;
14 #endif // __DEBUG__
15     cout << MAX_FUN(1+3, 2+3) << endl;
16     SHOW_CODE_LOCATION();
17     int i = 1, j = 2;
18     SWAP_INT(i,j);
19     cout << i << "," << j << endl;
20     bitset<30> bs(27);
21     cout << TEST(bs,10) << endl;
22     system("pause");
23     return 0;
24 }

 

 

在头文件中均有标记。

(1) 定义常量,该常量会在预编译期间将所有的MAX 替换为 1000. 但是不建议这样使用。因为该替换发生在预编译期间,不是编译期间。所以这个MAX没有存在在编译的符号表中。一旦出错,那么提示就是一个 1000. 没有任何提示。在effective C++ 中建议使用const 。

(2) 定义函数,这里注意一下,需要将a,b 都用小括号括起来,用来防止给这个函数传入的是表达式。

(3) 用于输出文件名和文件行号。

(4) 可以在define定义中写多行程序,每一行结尾用\, 最后一行除外。注意在定义中,不能有空格,不能有空行。

(5) 可以直接定义一个变量,然后在cpp代码中,通过检测该变量是否存在,来输出调试信息。

 

推荐阅读