如何用多语句定义一个c宏

How to define a c macro with multiple statement

我正在尝试定义一个有两个 line/statements 的宏,就像:

#define FLUSH_PRINTF(x) printf(x);fflush(stdout);

但由于 C 宏不能使用 ';' 的限制,它无法工作。

是否有任何合理的解决方法?

P.S.: 我知道上面的例子很奇怪,我应该使用类似普通函数的东西。但这只是一个我想质疑的简单例子关于如何定义多语句宏

现在是使用do { ... } while (0)成语的合适时机。 这也是使用variadic macro arguments.

的合适时机
#define FLUSH_PRINTF(...) \
    do { \
        printf(__VA_ARGS__); \
        fflush(stdout); \
    } while (0)

您也可以使用包装函数来执行此操作,但由于使用 vprintf.

涉及额外的样板,因此需要输入更多内容
 #include <stdarg.h>
 #include <stdio.h>

 /* optional: */ static inline 
 void
 flush_printf(const char *fmt, ...)
 {
     va_list ap;
     va_start(ap, fmt);
     vprintf(fmt, ap);
     va_end(ap);
     fflush(stdout);
 }

最好的解决办法是改写一个函数。我不明白你为什么首先需要一个宏。

至于如何用宏来实现,简单的包裹在{}:

#define FLUSH_PRINTF(x) { printf(x);fflush(stdout); }

根据 C11 6.8,这完全没问题,导致 复合语句:

statement:
  labeled-statement
  compound-statement
  expression-statement
  selection-statement

如果您希望允许不带大括号的危险样式 if 语句(坏主意),例如:

if(x)
  FLUSH_PRINTF(x);
else
  FLUSH_PRINTF(y);

那么你必须使用 do while(0) 技巧来包装宏:

#define FLUSH_PRINTF(x) do { printf(x);fflush(stdout); } while(0)

在宏中使用多重表达式

#define FLUSH_PRINTF(x) (printf(x), fflush(stdout))