macro definitions (#define, #undef)
To define preprocessor macros we can use #define. Its format is:#define identifier replacement
When the preprocessor encounters this directive, it replaces any occurrence of identifier in the rest of the code byreplacement. This replacement can be an expression, a statement, a block or simply anything. The preprocessor does not understand C++, it simply replaces any occurrence of identifier by replacement.
|
|
After the preprocessor has replaced TABLE_SIZE, the code becomes equivalent to:
|
|
This use of #define as constant definer is already known by us from previous tutorials, but #define can work also with parameters to define function macros:
|
|
This would replace any occurrence of getmax followed by two arguments by the replacement expression, but also replacing each argument by its identifier, exactly as you would expect if it was a function:
|
|
5 7 |
Defined macros are not affected by block structure. A macro lasts until it is undefined with the #undef preprocessor directive:
|
|
This would generate the same code as:
|
|
Function macro definitions accept two special operators (# and ##) in the replacement sequence:
If the operator # is used before a parameter is used in the replacement sequence, that parameter is replaced by a string literal (as if it were enclosed between double quotes)
|
|
This would be translated into:
|
|
The operator ## concatenates two arguments leaving no blank spaces between them:
|
|
This would also be translated into:
|
|
Because preprocessor replacements happen before any C++ syntax check, macro definitions can be a tricky feature, but be careful: code that relies heavily on complicated macros may seem obscure to other programmers, since the syntax they expect is on many occasions different from the regular expressions programmers expect in C++.
本文介绍C++中使用预处理器指令#define定义宏的方法,包括常量宏定义及带参数的函数宏定义。此外还介绍了如何使用#undef取消宏定义,以及宏定义中特殊操作符#和##的作用。
1016

被折叠的 条评论
为什么被折叠?



