转自 http://blog.csdn.net/beanjoy/article/details/7577944
有如下C++代码:
- #include <iostream>
- using namespace std;
- #define A(exp) cout << "I am "#exp << endl;
- #define B(exp) cout << sz##exp << endl;
- #define C(exp) cout << #@exp << endl;
- int main()
- {
- char *szStr = "test";
- A(Chinese); // cout << "I am ""Chinese" << endl;
- B(Str); // cout << szStr << endl;
- C(a); // cout << 'a' << endl;
- C(ab); // cout << 'ab' << endl;
- return 0;
- }
运行结果如下:
展开的时候,#exp被扩展成字符串,##exp被扩展成子串,#@exp被扩展成字符。
注意:#@只实用于windows系统,MSDN如下说明
Operator | Action |
---|---|
Stringizing operator (#) | Causes the corresponding actual argument to be enclosed in double quotation marks |
Charizing operator (#@) | Causes the corresponding argument to be enclosed in single quotation marks and to be treated as a character (Microsoft Specific) |
Token-pasting operator (##) | Allows tokens used as actual arguments to be concatenated to form other tokens |
可用作自定义ASSERT:
- #include <iostream>
- using namespace std;
- #ifdef ASSERT
- #undef ASSERT
- #endif
- #define ASSERT(exp)\
- if (!(##exp))\
- {\
- cout << "an error occured while execute \""#exp"\" at "\
- << __FILE__ << "(" << __LINE__ << ")" << endl;\
- exit(-1);\
- }
- int main()
- {
- int a = 0;
- int b = 1;
- ASSERT(a == b);
- cout << "test" << endl;
- return 0;
- }