Home > Backend Development > C++ > body text

In C language, health macro

王林
Release: 2023-09-03 18:09:08
forward
643 people have browsed it

In C language, health macro

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.

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</p><p>", a, b);
}
Copy after login

After preprocessing the code will look 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</p><p>", a, b);
}
Copy after login

Output

a = 10, b = 21
Copy after login

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.

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</p><p>", a, b);
}
Copy after login

Output

a = 11, b = 21
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template