macro definitions (#define, #undef)

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 by replacement . 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 .

1
2
3
#define TABLE_SIZE 100
int table1[TABLE_SIZE];
int table2[TABLE_SIZE]; 


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

1
2
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// function macro
#include 
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;
}
5
7


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

1
2
3
4
5
#define TABLE_SIZE 100
int table1[TABLE_SIZE];
#undef TABLE_SIZE
#define TABLE_SIZE 200
int table2[TABLE_SIZE];


This would generate the same code as:

1
2
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)

1
2
#define str(x) #x
cout << str(test);


This would be translated into:

 
cout << "test";


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

1
2
#define glue(a,b) a ## b
glue(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++.

你可能感兴趣的:(macro definitions (#define, #undef))