We are all familiar with the working of macros in languages like C. There are certain situations in which macro expansions can lead to undesirable results because of accidental capture of identifiers.
For example:
C++
#include <iostream>
using namespace std;
#define INCI(i) do { int x = 0; ++i; } while(0)
int main()
{
int x = 4, y = 8;
INCI(x);
INCI(y);
cout << "x = " << x << ", y = " << y << endl;
return 0;
}
|
C
#include <stdio.h>
#define INCI(i) do { int x = 0; ++i; } while(0)
int main( void )
{
int x = 4, y = 8;
INCI(x);
INCI(y);
printf ( "x = %d, y = %d\n" , x, y);
return 0;
}
|
The code is actually equivalent to:
C++
#include <iostream>
using namespace std;
int main()
{
int x = 4, y = 8;
do { int x = 0; ++x; } while (0);
do { int x = 0; ++y; } while (0);
cout << "x = " << x << ", y = " << y << endl;
return 0;
}
|
C
#include <stdio.h>
int main( void )
{
int x = 4, y = 8;
do { int x = 0; ++x; } while (0);
do { int x = 0; ++y; } while (0);
printf ( "x = %d, y = %d\n" , x, y);
return 0;
}
|
Output:
x = 4, y = 9
The variable a declared in the scope of the main function is overshadowed by the variable a in the macro definition so a = 4 never gets updated (known as accidental capture).
Hygienic macros
Hygienic macros are macros whose expansion is guaranteed not to cause the accidental capture of identifiers. A hygienic macro doesn’t use variable names that can risk interfering with the code under expansion.
The situation in the above code can be avoided simply by changing the name of the variable in the macro definition, which will produce a different output.
C++
#include <iostream>
using namespace std;
#define INCI(i) do { int m = 0; ++i; } while(0)
int main()
{
int x = 4, y = 8;
INCI(x);
INCI(y);
cout << "x = " << x << ", y = " << y << endl;
return 0;
}
|
C
#include <stdio.h>
#define INCI(i) do { int m = 0; ++i; } while(0)
int main( void )
{
int x = 4, y = 8;
INCI(x);
INCI(y);
printf ( "x = %d, y = %d\n" , x, y);
return 0;
}
|
Output:
x = 5, y = 9
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
21 Jun, 2022
Like Article
Save Article