C Reference ยท Preprocessor
The #undef directive
Reference for the C #undef directive: remove a macro, redefine it safely, unwrap library macros and understand why undefining a missing macro is fine.
#undef removes a macro definition. After it, the name is an ordinary identifier again (or can be defined afresh with a different replacement). It is useful for limiting a macro to a region of a file, for redefining a configuration value, and for getting a real function back when a library defines a macro with the same name.
Undefining a name that is not currently a macro is allowed and does nothing.
#define LIMIT 10 /* ... uses of LIMIT ... */ #undef LIMIT
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
#undef identifier
| Name | Description |
|---|---|
identifier |
The macro to remove. Extra tokens after it are not allowed (compilers warn). |
Errors / undefined behavior: #undef of a predefined macro such as __FILE__, __LINE__, __DATE__, __TIME__, __STDC__ or defined is undefined behavior. Undefining a standard library macro (like assert, NULL or EOF) is also unsafe in general, except where the standard explicitly allows it.
Usage notes
- Common pattern: define, use, then
#undeffor macros that exist only to generate code, such as X macros. - Unwrap a library macro. Some headers define a macro with a function's name (for example, for speed).
#undef namemakes a call refer to the real function. In standard C, the parenthesized call(name)(args)does the same without touching the macro. - Redefining without
#undefto a different replacement is an error or warning; do#undeffirst when you need to change a value. - Headers should not leak helper macros.
#undefthem before the end of the header. - Order matters: only code after the directive is affected; text before it was already expanded.
- Command line:
-UNAMEundefines a macro before the file is read.
Related
- #define, #if, #ifdef, #ifndef, Predefined macros
- Tutorial: The preprocessor