Handout 11

#define and #undef*


Syntax

#define name <token_sequence>

Description

The#define directive defines a macro. Macros provide a mechanism for token replacement with or without a set of formal, function-like parameters.

Each occurrence of name in your source code following this control line will be replaced in the original position with the token_sequence. Such replacements are known as macro expansions. The token sequence is sometimes called the body of the macro.

An empty token sequence results in the removal of each affected macro identifier from the source code.

After each individual macro expansion, a further scan is made of the newly expanded text. This allows for the possibility of nested macros: The expanded text can contain macro identifiers that are subject to replacement. However, if the macro expands into what looks like a preprocessing directive, such a directive will not be recognized by the preprocessor.

Syntax

#undef name

Description

You can undefine a macro using the #undef directive. #undef detaches any previous token sequence from the macro identifier; the macro definition has been forgotten, and the macro identifier is undefined. No macro expansion occurs within #undef lines.

Example

1    #include <iostream>
2    using namespace std;
3    #define MY_STUFF 8
4    #define YOUR_STUFF 9
5
6    int main() {
7      int i;
8
9      cout << MY_STUFF << " " << YOUR_STUFF << endl;
10
11   #undef YOUR_STUFF
12
13     cout << MY_STUFF << endl;
14
15   #define YOUR_STUFF (1 * 2 * 3 * 4)
16
17     cout << MY_STUFF << " " << YOUR_STUFF << endl;
18
19   #define YOUR_STUFF (17 % 3)
20
21     cout << MY_STUFF << " " << YOUR_STUFF << endl;
22
23   #define SOME_OTHER_STUFF 10
24
25     for(i = 0; i < SOME_OTHER_STUFF; i++) cout << i;
26
27     return 0;
28   }

Output from the above is:

8 9
8
8 24 
8 2
0123456789


* portions from Borland C++ 4.5 Help. Source.