macro definitions (#define, #undef)

来源:互联网 发布:防范电信网络诈骗图片 编辑:程序博客网 时间:2024/05/17 13:06

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.

123
#define TABLE_SIZE 100int table1[TABLE_SIZE];int table2[TABLE_SIZE]; 


After the preprocessor has replaced TABLE_SIZE, the code becomes equivalent to:

12
int table1[100];int table2[100]; 


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:

 
#define getmax(a,b) a>b?a:b 


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:

1234567891011121314
// function macro#include <iostream>using namespace std;#define getmax(a,b) ((a)>(b)?(a):(b))int main(){  int x=5, y;  y= getmax(x,2);  cout << y << endl;  cout << getmax(7,x) << endl;  return 0;}
57


Defined macros are not affected by block structure. A macro lasts until it is undefined with the #undef preprocessor directive:

12345
#define TABLE_SIZE 100int table1[TABLE_SIZE];#undef TABLE_SIZE#define TABLE_SIZE 200int table2[TABLE_SIZE];


This would generate the same code as:

12
int table1[100];int table2[200];


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)

12
#define str(x) #xcout << str(test);


This would be translated into:

 
cout << "test";


The operator ## concatenates two arguments leaving no blank spaces between them:

12
#define glue(a,b) a ## bglue(c,out) << "test";


This would also be translated into:

 
cout << "test";


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++.
原创粉丝点击