我经常希望我有一种简单的方法来构造一个带有Sprintf/Snprint tf的字符串,而不需要定义一个本地数组,如下所示:
char str[256];
snprintf(str, sizeof(str), format, ...);
use_string(str);
我突然想到,我可以使用复合文字来执行此操作:
static inline char* snprintf_assert(char* str, int max_size, const char* format, ...) {
va_list arg;
va_start(arg, format);
int count = vsnprintf(str, max_size, format, arg);
va_end(arg);
assert(count >= 0 && count < max_size);
return str;
}
// Helper sprintf that allocates a buffer local to the block.
// It's using the fact that (char[N]){} will allocate a l-value
// with lifetime tied to the local block.
#define local_sprintf(N, ...) snprintf_assert((char[N]){}, N, __VA_ARGS__)
用途:
use_string(local_sprintf(256, format, ...));
我相信这是很好的定义,因为复合文字数组的生存期将与封闭的块绑定在一起.有什么理由可以避免这一点吗?