最近在看一些C++源代碼的時候發現很多的宏定義中使用了do {…} while(0)這樣的語法,當時覺得很奇怪,感覺這樣的語法并沒有意義,后來在網上查了相關的資料才發現它的微妙之處。 假如我們有這樣一個例子:
#define FUNC(x) func1(x);func2(x)int main(){ int x = 0; FUNC(x);}那么在編譯的預處理的過程中,編譯器會對宏進行展開:
int main(){ int x = 0; func1(x);func2(x);}這樣程序是沒有任何問題的。如果程序是這樣調用宏的呢?
#define FUNC(x) func1(x);func2(x);int main(){ int x = 0; if (test(x)) FUNC(x);}對宏進行展開:
int main(){ int x = 0; if (test(x)) func1(x);func2(x);}對代碼進行排版:
int main(){ int x = 0; if (test(x)) func1(x); func2(x);}那么這樣展開后,無論test(x)是否為true,程序都會執行func2(x),這就有可能會出現問題了。其實我們的目的是如果test(x)為true就執行func1(x)和func2(x),否則都不執行。 宏定義加上do(…)while(0)就可以解決這個問題了:
#define FUNC(x) do (func1(x);func2(x);) while(0)int main(){ int x = 0; if (test(x)) FUNC(x);}展開宏定義,程序變為:
int main(){ int x = 0; if (test(x)) do (func1(x);func2(x);) while(0)}這樣程序就能按照我們的想法運行了。
概括來說,宏定義中使用do(…)while(0)可以使得宏能夠不受大括號,分號等的影響,總是能夠按照預期的方式運行。
新聞熱點
疑難解答