Hygienic Macros in C

CServer Side ProgrammingProgramming

Here we will see the Hygienic Macros in C. We know the usage of macros in C. But sometimes, it does not return the desired results because of accidental capture of identifiers.

If we see the following code, we can see that it is not working properly.

Example

#include<stdio.h>
#define INCREMENT(i) do { int a = 0; ++i; } while(0)
main(void) {
   int a = 10, b = 20;
   //Call the macros two times for a and b
   INCREMENT(a);
   INCREMENT(b);
   printf("a = %d, b = %d\n", a, b);
}

After preprocessing the code will be like this −

Example

#include<stdio.h>
#define INCREMENT(i) do { int a = 0; ++i; } while(0)
main(void) {
   int a = 10, b = 20;
   //Call the macros two times for a and b
   do { int a = 0; ++a; } while(0) ;
   do { int a = 0; ++b; } while(0) ;
   printf("a = %d, b = %d\n", a, b);
}

Output

a = 10, b = 21

Here we can see the value is not updated for a. So in this case we will use the hygienic macros. These Hygienic macros are macros whose expansion is guaranties that it does not create the accidental capture of identifiers. Here we will not use any variable name that can risk interfacing with the code under expansion. Here another variable ‘t’ is used inside the macro. This is not used in the program itself.

Example

#include<stdio.h>
#define INCREMENT(i) do { int t = 0; ++i; } while(0)
main(void) {
   int a = 10, b = 20;
   //Call the macros two times for a and b
   INCREMENT(a);
   INCREMENT(b);
   printf("a = %d, b = %d\n", a, b);
}

Output

a = 11, b = 21
raja
Published on 08-May-2019 08:19:02
Advertisements