Here we will see hygiene macros in C. We know how to use macros in C. But sometimes, it doesn't return the expected result due to an unexpected capture of the identifier.
If we see the code below, we can see that it is not working properly.
#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</p><p>", a, b); }
After preprocessing the code will look like this -
#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</p><p>", a, b); }
a = 10, b = 21
Here we can see The value to a is not updated. So in this case we will use hygiene macro. The expansion of these hygiene macros guarantees that identifiers are not accidentally captured. Here we won't use any variable names that might interact with code in the extension. Here another variable "t" is used inside the macro. The program itself does not use it.
#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</p><p>", a, b); }
a = 11, b = 21
The above is the detailed content of In C language, health macro. For more information, please follow other related articles on the PHP Chinese website!