C/C++中可以用 #undef xxx 來取消宏xxx的定義。舉例如下
#undef命令可以取消定義一個名稱爲宏:
#undef name
這個命令使預處理器忘記name的所有宏定義。取消一個當前未定義宏的定義並不是錯誤。當一個名稱被取消定義之後,就可以向它提供一個全新的定義(使用#define),而不會產生任何錯誤。在#undef命令內部,並不會執行宏替換。
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
// xxx is defined
bool b = true;
#define xxx
#ifdef xxx
cout << "xxx is defined #1" << endl; // this line is printed
#endif
// undefine xxx
#ifdef xxx
#undef xxx
b = true;
#endif
#ifdef xxx
cout << "xxx is defined #2" << endl; // not printed
#endif
// define xxx again
if(b)
{
#define xxx
}
#ifdef xxx
cout << "xxx is defined #3" << endl; // printed
#endif
return 0;
}
結果輸出:
xxx is defined #1
xxx is defined #3