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?
PS: 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 .
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);
}
Use the multiple expression in macro
#define FLUSH_PRINTF(x) (printf(x), fflush(stdout))
The best solution is to write a function instead. I don't understand why you need a macro in the first place.
As for how to do it with a macro, simply wrap it in {}
:
#define FLUSH_PRINTF(x) { printf(x);fflush(stdout); }
This is perfectly fine as per C11 6.8, resulting in a compound-statement :
statement:
labeled-statement
compound-statement
expression-statement
selection-statement
If you wish to allow dangerous style if
statements with no braces (bad idea), such as:
if(x)
FLUSH_PRINTF(x);
else
FLUSH_PRINTF(y);
then you must use the do while(0)
trick to wrap the macro:
#define FLUSH_PRINTF(x) do { printf(x);fflush(stdout); } while(0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.