Coding Techniques
Variable Number of Arguments · Study material
Format into an exactly sized string with vsnprintf
Calling vsnprintf(NULL, 0, …) returns the length the result needs. Allocate that much, then format again with a copy of the va_list – the first pass used up the original.
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
/* Format into a new heap string of exactly the right size (like asprintf) */
static char *format(const char *fmt, ...) {
va_list ap, ap2;
va_start(ap, fmt);
va_copy(ap2, ap);
int len = vsnprintf(NULL, 0, fmt, ap); /* pass 1: measure */
va_end(ap);
char *s = len < 0 ? NULL : malloc((size_t) len + 1);
if (s != NULL)
vsnprintf(s, (size_t) len + 1, fmt, ap2); /* pass 2: write */
va_end(ap2);
return s;
}
int main(void) {
char *msg = format("%s scored %d/%d (%.1f%%)", "Asha", 47, 50, 94.0);
if (msg != NULL) {
printf("%s\n", msg);
free(msg);
}
return 0;
}
Asha scored 47/50 (94.0%)
Let the compiler check your printf-like functions
/* GCC and Clang: argument 2 is a printf format, checking starts at argument 3 */
__attribute__((format(printf, 2, 3)))
void log_msg(int level, const char *fmt, ...);
log_msg(1, "%d files", "three"); /* warning: format '%d' expects int */Without the attribute, mismatched arguments compile silently and fail at run time.
Prefer a typed alternative when you can
/* Variadic: no type checking, caller must pass the count */
int sum(int count, ...);
sum(3, 1, 2, 3);
/* Array + length: fully type-checked */
int sum_array(const int *a, size_t n);
sum_array((int[]){1, 2, 3}, 3); /* a compound literal makes calls just as short */ Good habits with variadic functions
- Document how the end of the list is marked.
- Read promoted types only: int, unsigned, long, double, pointers.
- Cast NULL sentinels:
(char *) NULL. - Pair every va_start/va_copy with va_end in the same function.
- Provide a v-version (taking va_list) of every printf-like function you write.