About #undef preprocessor directive in C

#undef preprocessor directive can undefine the macro or other constant which we have defined by #define preprocessor directive. Sometimes we need to undefine any constant when we want to use it for a limited scope in our program.

The #undef preprocessor directive serves the purpose of undefining the constant or macros defined by #define.

Let’s see an example to use #undef preprocessor directive.

#include <stdio.h>
#define MY_WEIGHT 72

int main(){
  printf("%d\n", MY_WEIGHT);
  return 0;
}

If you write this code then compile and run it, you will get the following output.

undef-preprocessor-directive-in-c-has-undef-in-c

But if you undefine the variable MY_WEIGHT by #undef then you will get an error like this;

#include <stdio.h>
#define MY_WEIGHT 72
#undef MY_WEIGHT

int main(){
  printf("%d\n", MY_WEIGHT);
  return 0;
}
error: 'MY_WEIGHT' undeclared (first use in this function)

C program using #undef preprocessor directive

Suppose you want to determine the area of a circle where the value of PI and the radius of circle is defined by #define. Although we can write this program in many ways but here we will use #define and #undef for our understanding. So, lets see the program bellow;

// C program using #undef preprocessor directive

#include <stdio.h>
#define PI 3.1416
#define RADIUS 5

float area_one = PI * (RADIUS * RADIUS);

#undef PI
#undef RADIUS

int main(){
  printf("Area of circle before using #undef is = %.3f\n", area_one);
  return 0;
}

Output :

Area of circle before using #undef is = 78.540

But if you write the code in following way then the compiler will through an error as like as given bellow;

#include <stdio.h>
#define PI 3.1416
#define RADIUS 5

float area_one = PI * (RADIUS * RADIUS);

#undef PI
#undef RADIUS

float area_two = PI * (RADIUS * RADIUS);

int main(){
  printf("Area of circle before using #undef is = %.3f\n", area_one);
  printf("Area of circle after using #undef is = %.3f\n", area_two);
  return 0
}
error: 'PI' undeclared here (not in a function)
error: 'RADIUS' undeclared here (not in a function)