C Programming Tutorial
The #undef preprocessor directive is used to undefine the constant or macro defined by #define.
Description
In the C Programming Language, the #undef directive tells the preprocessor to remove all definitions for the specified macro. A macro can be redefined after it has been removed by the #undef directive.
Once a macro is undefined, an #ifdef directive on that macro will evaluate to false.
Syntax:
#undef token
Let's see a simple example to define and undefine a constant.
#include <stdio.h>
#define PI 3.14
#undef PI
main() {
printf("%f",PI);
}
Output:
Compile Time Error: 'PI' undeclared
The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.
Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.
#include
#define number 5
int square=number*number;
#undef number
main() {
printf("%d",square);
}
Output:
25
Example
The following example shows how to use the #undef directive:
/* Example using #undef directive by C programming */
#include <stdio.h>
#define YEARS_OLD 10
#undef YEARS_OLD
int main()
{
#ifdef YEARS_OLD
printf("c programming is over %d years old.\n", YEARS_OLD);
#endif
printf("c programming is a great resource.\n");
return 0;
}
In this example, the YEARS_OLD macro is first defined with a value of 10 and then undefined using the #undef directive. Since the macro no longer exists, the statement #ifdef YEARS_OLD evaluates to false. This causes the subsequent printf function to be skipped.
Here is the output of the executable program:
c programming is a great resource.