I have tried this:
#define format(f, ...) \
int size = strlen(f) + (sizeof((int[]){__VA_ARGS__})/sizeof(int)) + 1); \
char *buf = malloc(size); \
snprintf(buf, size, f, __VA_ARGS__); \
buf
But it returns a lot of syntactic errors. How do I do this properly?
C macros are not functions but 1:1 substitutions. So if you want to use your macro like this:
You get this:
Which does not make any sense. In your case you are better off defining an inline function which should not be any worse in terms of performance on a decent compiler.
If it really has to be a macro and you are on GCC, you can use the compound statement to achieve your goal. It allows you to do this:
mystring = ({ statement1, statement2, ..., statementN})which will execute all your statements in a local scope and then assignstatementNtomystring. However it will make your code non-portable and be a hell to debug.So here you go, but please don’t use this in real applications:
I’m serious. Don’t use this. Use an inline function. You can also have variadic arguments in normal functions, using
va_argandva_start: