7

I am trying to define a macro that has two line/statements, it's like:

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

but it can't work due to the limit that C macros cannot work with ';'.

Is there any reasonable way to work around it?

P.S.: I know the upper example is weird and I should use something like a normal function. but it's just a simple example that I want to question about how to define a multiple statement Macro.

pambda
  • 2,930
  • 2
  • 22
  • 32
  • 3
    `but it can't works due to the limit that C Macro can not work with ';'.` What do you mean? Why not write a function? – tkausl May 17 '18 at 14:19
  • Please post a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – MikeCAT May 17 '18 at 14:19
  • If you do want to do that: `#define FLUSH_PRINTF(x) {printf(x); fflush(stdout);}` – Jose May 17 '18 at 14:21
  • Shouldn't fflush be avoided? – Kami Kaze May 17 '18 at 14:24
  • 1
    @KamiKaze: `fflush` is fine for output streams - it's UB for input streams in general (although supported on some platforms). – Paul R May 17 '18 at 14:27
  • @tkausl I know the upper example is weird and I should use something like a normal function. but it's just a simple example that I want to question about how to define a multiple statement Macro. – pambda May 17 '18 at 14:43

2 Answers2

11

This is an appropriate time to use the do { ... } while (0) idiom. This is also an appropriate time to use variadic macro arguments.

#define FLUSH_PRINTF(...) \
    do { \
        printf(__VA_ARGS__); \
        fflush(stdout); \
    } while (0)

You could also do this with a wrapper function, but it would be more typing, because of the extra boilerplate involved with using 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);
 }
zwol
  • 135,547
  • 38
  • 252
  • 361
  • 1
    Why an inline function? A normal function would work just as well. – Jabberwocky May 17 '18 at 14:34
  • @MichaelWalz I know the upper example is weird and I should use something like a normal function. but it's just a simple example that I want to question about how to define a multiple statement Macro. – pambda May 17 '18 at 14:44
  • @MichaelWalz I suppose it doesn't need to be inline, no. – zwol May 17 '18 at 14:45
2

Use the multiple expression in macro

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

Abhinav
  • 21
  • 2