Skip to content
Tutorials Center
My learning

Topics

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.

C
#define LIMIT 10
/* ... uses of LIMIT ... */
#undef LIMIT

Try it

C Redefining a macro in stages

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.

C Scoping a helper macro

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

C
#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 #undef for 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 name makes a call refer to the real function. In standard C, the parenthesized call (name)(args) does the same without touching the macro.
  • Redefining without #undef to a different replacement is an error or warning; do #undef first when you need to change a value.
  • Headers should not leak helper macros. #undef them before the end of the header.
  • Order matters: only code after the directive is affected; text before it was already expanded.
  • Command line: -UNAME undefines a macro before the file is read.