c - How to write a macro that does malloc, formats a string and then returns the formatted string? -
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 returns lot of syntactic errors. how do properly?
c macros not functions 1:1 substitutions. if want use macro this:
mystring = format("%d", 5);
you this:
mystring = int size = strlen(f) + (sizeof((int[]){5})/sizeof(int)) + 1); \ char *buf = malloc(size); \ snprintf(buf, size, f, 5); \ buf;
which not make sense. in case better off defining inline function should not worse in terms of performance on decent compiler.
if really has macro , on gcc, can use compound statement achieve goal. allows this: mystring = ({ statement1, statement2, ..., statementn})
execute statements in local scope , assign statementn
mystring
. make code non-portable , hell debug.
so here go, please don't use in real applications:
#define format(f, ...) \ ({ int size = snprintf(null, 0, f, __va_args__) + 1;\ char * buf = malloc(size);\ snprintf(buf, size, f, __va_args__); buf; })
i'm serious. don't use this. use inline function. can have variadic arguments in normal functions, using va_arg
, va_start
:
inline char * format(f, ...) { va_list args; va_start(args, f); int size = vsnprintf(null, 0, f, args) + 1; char * buf = malloc(size); vsnprintf(buf, size, f, args); return buf; }
Comments
Post a Comment