Removing definitions with #undef
What you'll learn: How to use the #undef directive to cancel a previously defined macro and gain manual control over your preprocessor symbols.
The "Eraser" of the Preprocessor
So far, you have learned how to use #define to create constants or macros. Think of #define like writing a name on a whiteboard with a permanent marker. It stays there for the rest of your code to see. However, sometimes you need to wipe that whiteboard clean.
The #undef directive is your eraser. It tells the preprocessor to forget that a specific macro ever existed. Once a name has been "undefined," it is as if it was never created. If you try to use it later in the code, the compiler will treat it like any other unknown word, likely resulting in an error.
Why would you "undefine" something?
You might wonder why you would bother creating a rule only to delete it. The most common reason is scoping control. In C, macros are global—once defined, they persist until the end of the file. If you only need a macro for a tiny section of code and want to prevent it from accidentally messing up other parts of your program, you "wrap" your code with a #define at the top and an #undef at the bottom.
Another common use is redefinition. C doesn't like it when you try to define the same name twice with different values. By using #undef first, you clear the old definition away so you can safely set a new one.
Seeing #undef in action
In the following example, we create a temporary limit, use it, and then erase it to keep our code "clean."
#include <stdio.h>
// 1. Define a macro
#define MAX_SPEED 100
int main() {
printf("The current limit is: %d\n", MAX_SPEED);
// 2. Erase the macro definition
#undef MAX_SPEED
// 3. Now, MAX_SPEED no longer exists.
// The line below would cause a compiler error if uncommented:
// printf("The limit is still: %d", MAX_SPEED);
return 0;
}
By using #undef, you ensure that MAX_SPEED doesn't leak into other parts of a large project where that name might mean something completely different. It is a tool for precision, helping you keep your preprocessor environment tidy and predictable.
Key takeaway
Use #undef to remove a macro definition, preventing name conflicts and keeping your preprocessor symbols limited to only where they are needed.