Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 201
pambda Avatar asked May 17 '18 14:05

pambda


2 Answers

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);
 }
like image 84
zwol Avatar answered Sep 29 '22 00:09

zwol


Use the multiple expression in macro

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

like image 23
Abhinav Avatar answered Sep 29 '22 00:09

Abhinav