变量 C 宏函数

Variables C macro function

这个宏中发生了什么?我知道 #test 将此参数扩展为文字文本。但是 pre;test; 是做什么的呢?

#define MACRO_FN(test, pre, repeat, size)    \
  do {                                     \
    printf("%s: ", #test);                 \
    for (int i = 0; i < repeat; i++) {     \
      pre;                                 \
      test;                                \
    }                                      \
  } while (0)

这个是这样用的

MACRO_FN(a_func(an_array, size),, var1, size);

这里的双逗号是什么意思?

pretest好像是两个函数。 根据它的写法,我们可以猜测 pre 是在 test.

之前调用的函数

双逗号没有特殊含义。就是这里因为省略了第二个参数(pre)

编辑:作为旁注,那种宏 "should be avoided like plague",如@Lundin 所说。

这是一个最小的例子:

#define repeat 5    // I added this, because 'repeat' is not mentionned in your question

#define MACRO_FN(test, pre, var1, size)    \
  do {                                     \
    printf("%s: ", #test);                 \
    for (int i = 0; i < repeat; i++) {     \
      pre;                                 \
      test;                                \
    }                                      \
  } while (0)

void foo()
{
}

void func(int a, int b)
{
}

int main()
{
  MACRO_FN(func(2, 3), foo(), var1, size);
}

预处理后,代码等同于:

int main()
{
  printf("%s: ", "func(2,3)");
  for (int i = 0; i < 5; i++)
  {
    foo();
    func(2, 3);
  }
}

因此该宏是一个包装器,它打印函数名称及其参数,因为它是用宏调用的,并执行第一个参数中指定的函数 repeat 次(无论 repeat 是什么) .如果省略第二个参数,则具有该名称的函数很简单,不会在前面提到的函数之前调用,如下例所示:

int main()
{
  MACRO_FN(func(2, 3),, var1, size);
}

预处理后,代码等同于:

int main()
{
  printf("%s: ", "func(2,3)");
  for (int i = 0; i < 5; i++)
  {
    ;
    func(2, 3);
  }
}

:

为简洁起见,我从等效程序中删除了 do while(0),阅读 this SO article 了解更多信息: