【Macro definition】——Why use do{} while(0) structure

Do not use do while(0)

#define MY_MACRO(x) \
    printf("Hello "); \
    printf("%d", x);

If there is an if judgment code

if  (x)
	MY_MACRO(x)

Then the macro expansion is

if (x)
    printf("Hello ");
    printf("%d", x);

The second statement is not executed when the if is true

The above problem can be {}solved with

#define MY_MACRO(x) {
      
       \
    printf("Hello "); \
    printf("%d", x);  \
    }

if (a)
  MY_MACRO(a);
else
  MY_MACRO(b);

After the macro expansion is

if (a)
 {
    
    
    printf("Hello ");
    printf("%d", x);
 };
else
  MY_MACRO(b);

In the if-else statement, };this structure will report an error

Use the do while(0) construct

#define MY_MACRO(x) do {
      
       \
    printf("Hello "); \
    printf("%d", x); \
} while(0)

Perfectly solve the above problems

if (a)
  do
  {
    
    
    printf("Hello ");
    printf("%d", x);
  } while (0);
else
  do
  {
    
    
    printf("Hello ");
    printf("%d", x);
  } while (0);

Guess you like

Origin blog.csdn.net/tyustli/article/details/132031189