phougatv
phougatv

Reputation: 1014

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?

Upvotes: 0

Views: 1206

Answers (3)

Kiva
Kiva

Reputation: 53

A rule in MISRA is that #undef can make it unclear which macros exist at a particular point within the translation unit. Therefore , it is advisory not to use #undef in order not to get such behaviour.

Upvotes: 1

Chirag Bhatia - chirag64
Chirag Bhatia - chirag64

Reputation: 4516

#define replaces strings in code during compile time. So when the compiler processes

#define P (i + j), it replaces every instance of P that it sees with (i + j) until it reaches the point where it reads #undef P. This tells the compiler to stop replacing P with (i + j).

As a result, the last instance of P (after the #undef statement) is not replaced, and since there is no variable P declared above in the code, it results to an error.

This was not a problem in the first program since you have already declared k in the line

int i,j,k=0;

Upvotes: 2

Jack Aidley
Jack Aidley

Reputation: 20107

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.

Upvotes: 1

Related Questions