C #undef
Directive
The #undef
directive in C is used to undefine a previously defined macro. It is often employed to remove or reset a macro definition within the scope of a program.
Example
#include <stdio.h>
#define PI 3.14159 // Define PI macro
int main() {
printf("Value of PI: %f\n", PI);
#undef PI // Undefine PI macro
#ifdef PI
printf("PI is still defined.\n");
#else
printf("PI is undefined.\n");
#endif
return 0;
}
Output
Value of PI: 3.141590
PI is undefined.
Explanation
- In the example, we first define a macro
PI
with a value of3.14159
. - After using it in the
printf
statement, we use#undef PI
to undefine thePI
macro. Subsequently, we check ifPI
is still defined using#ifdef
. - Since we've undefine the macro, the output shows that
PI
is undefined.
Use
- Conditional Compilation: The
#undef
directive is often used in conjunction with conditional compilation to selectively define or undefine macros based on certain conditions.
- Conditional Compilation: The
- Macro Redefinition: It allows for the redefinition of macros within different parts of the code, allowing flexibility in macro usage.
Summary
#undef
is used to undefine a previously defined macro.- It is commonly used for conditional compilation and macro redefinition.
- Undefining a macro makes it undefined and renders it unusable in the remaining code.