Hygienic Macros in C


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
", 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
", 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
", a, b); }

Output

a = 11, b = 21

Updated on: 30-Jul-2019

396 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements