Preprocessor – the #undef Directive

Behaviour of the #undef directive is the same in both C and C++.

Purpose

It is used to undefine a macro.

A macro is an identifier (or label) followed by replacement text.

There is only a single namespace for macros. A program which redefines an existing macro is considered to be malformed – even though most compilers only generate a warning instead of an error.

Format

#undef MACRO_NAME

All preprocessor directives begin with the # symbol. It must be the first character on the line or the first character on the line following optional white space.

Some early compilers flagged an error if # was not the first character on the line.

Spaces or tabs are permitted between the # and undef, but not escape characters or other symbols or macros. The preprocessor removes whitespace and concatenates the # and undef together.

The following are valid uses:

#undef my_macro
#    undef      my_macro
     # undef my_macro
# /* comments are whitespace */ undef my_macro

The following are invalid uses:

#define empty_macro
// #empty_macro is not a valid preprocessor directive
#   empty_macro undef my_macro
// #\ is not a valid preprocessor directive
# \t undef my_macro
// #" is not a valid preprocessor directive
# "" undef my_macro

If the specified macro name does not exist, nothing happens.

If the specified macro name exists, its name, parameter list, and replacement text is removed.

Conceptually, macros are stored in a 3 column table:

|------------|----------------|------------------|
| Macro Name | Parameter List | Replacement Text |
|------------|----------------|------------------|
| my_macro   |                | // some text     |
|------------|----------------|------------------|
| macro_2a   | a, b           | ((a)*(b))        |
|------------|----------------|------------------|

When we #undef a macro, we remove it from the table.

A program is malformed if anything other than whitespace (comments count as whitespace) and a newline character follow the macro name.