pambda
pambda

Reputation: 3180

How to define a c macro with multiple statement

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.

Upvotes: 7

Views: 9931

Answers (2)

Abhinav
Abhinav

Reputation: 31

Use the multiple expression in macro

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

Upvotes: 3

zwol
zwol

Reputation: 140559

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);
 }

Upvotes: 11

Related Questions