使用#define取代文字

Compile幕後中有介紹過preprocessor,而在幾乎每一個C++ 程式中都有以#作為開頭,不以;做結的程式:

1
2
# include <iostream>
# define N 81

這些皆是Preprocess指令的範疇,以下的內容是關於常見的preprocess指令:# define,功能包括:

宣告某一代號的值,以方便取代

1
2
3
#define and &&
#define or ||
#define not !

用於程式裡頭即能以 and 代替 && ,如:

1
if((a==0)and(b==0)){} //等效於 if((a==0)&&(b==0)){}

產生以符號代表常數,稱為符號常數

1
#define N 81

產生以符號代表的一系列操作,稱為巨集

1
#define PRODUCT(x,y) (x*y)

條件式編譯時,宣告某一個代號已經被設定

就如C++ 中有if-else 具有選擇性的功能,前處理指令中有各種語法,可以有選擇性地執行某些前處理指令,或是編譯原始程式碼的某些部分。條件式編譯的應用之處則如程式在debug與release階段被預期有不同的表現,在debug模式也許會需要程式能夠提供越詳盡的資訊越好,而在release模式則需要扼要的資訊即可。以下用一個小例子來呈現:

Debug mode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#define debug
#include <iostream>
using namespace std;

#ifdef debug
#define FLAG cout<<"Successfully print out Hello world"<<endl
#else
#define FLAG
#endif

int main(){
cout<<"Hello world"<<endl;
FLAG;
return 0;
}

在檔案的開頭debug有被定義過,#ifdef debug成立,於是程式就會有選擇性的只編譯上方第一個FLAG的內容,輸出如下:

1
2
Hello world
Successfully print out Hello world

Release mode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#define release
#include <iostream>
using namespace std;

#ifdef debug
#define FLAG cout<<"Successfully print out Hello world"<<endl
#else
#define FLAG
#endif

int main(){
cout<<"Hello world"<<endl;
FLAG;
return 0;
}

在檔案的開頭debug沒有被定義過,#ifdef debug不成立,於是程式就會有選擇性的只編譯第二個FLAG的內容,輸出如下:

1
Hello world

reference: <<C++程式設計與應用>>