In ANSI C89, there are 6 printf functions: printf sprintf fprintf vprintf vsprintf vfprintf Other C versions add more: dprintf snprintf asprintf vdprintf vsnprintf vasprintf The sole difference between these functions is the format of input and the source of output. It would make sense to generalize this class of functions in a implementation of printf. Ideally down into one function that constructs and outputs the formatted string which the 12 functions can wrap around or be based upon. Some simple optimizations can be made already, all printf functions wrap around their varaidic forms, which cuts the list in half. printf and dprintf can both be thought of as wrappers, which reduces the now 6 functions needed into 4: vsprintf vfprintf vsnprintf vasprintf sprintf was a bad idea for the same reason gets was (in fact, GCC will throw a warning if it detects the use of either of those in almost every case). snprintf is theoretically different because it needs an output limit, but the behaviour of sprintf can be replicated by setting that limit to SIZE_MAX or similar. The 3 functions left are vfprintf, vasprintf, and vsnprintf. There is a straightforward way to reduce these down into one function, to vasprintf a dynamically allocated string, output it with memcpy or fputs, then free it. The problem with this approach is that it is inefficient. Even if using a vector that doubles in size when expanding to be O(log n), there are redundant allocations. If the formatted result is especially large, it will take up a large amount of memory. Trying to generalize printf functions that outputs the string as its constructed is a harder and more interesting problem. # The art of transmutation and opaqueness C89 defines qsort as: void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); The first 3 arguments are the parameters for an array, with the last being a function to pass the elements to (often a wrapper around strcmp, the comparison operat...
First seen: 2025-11-28 19:42
Last seen: 2025-11-28 23:42