Search code examples
cundefinedpreprocessor-directive

Using #undef preprocessor directive


Here are the 2 programs with very minor change.


Practice.c

#include <stdio.h>
#define P (i+j)

main()
{
  int i,j,k=0;
  printf("\nI = ");
  scanf("%d",&i);
  printf("\nJ = ");
  scanf("%d",&j);
  k=P;
  printf("\nValue of Defined Macro P = %d\n",k);

  #undef P
    printf("\nValue of Undefined Macro P = %d\n",k);
}

Output of the above program is:

I = 5

J = 9

Value of Defined Macro P = 14

Value of Undefined Macro P = 14


New.c

#include <stdio.h>
#define P (i+j)

main()
{
  int i,j,k=0;
  printf("\nI = ");
  scanf("%d",&i);
  printf("\nJ = ");
  scanf("%d",&j);
  k=P;
  printf("\nValue of Defined Macro P = %d\n",P);

  #undef P
    printf("\nValue of Undefined Macro P = %d\n",P);
}

Output of the above program is :

Practice.c: In function 'main':
Practice.c:15:48: error: 'P' undeclared (first use in this function)
    printf("\nValue of Undefined Macro P = %d\n",P);
                                               ^
Practice.c:15:48: note: each undeclared identifier is reported only once for eac
h function it appears in


Now I want to know that why did Practice.c got successfully compiled and executed, where I used variable k to display the output, and why did New.c displayed error on using Macro Template P directly?


Solution

  • Preprocessor directives are replaced where they occur. The variable k is set to 14 on the line where you write k=P which is exactly equivalent to writing k=14 so it still has its value after the #undef.