简体   繁体   中英

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?

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 .

#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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM