In C, can a function that accepts a variable argument list forward that same list to another function? (For example, wrap printf by calling vprintf with the captured va_list.)
-
AYes, by capturing with va_start and forwarding to a v* function (e.g., vprintf)
-
BNo, a va_list cannot be passed to any other function
-
COnly on UNIX systems
-
DOnly if all arguments are integers
-
EOnly if you avoid using va_end
Answer
Correct Answer: Yes, by capturing with va_start and forwarding to a v* function (e.g., vprintf)
Explanation
Introduction / Context:Wrappers around variadic interfaces are common. The correct pattern is to collect the arguments with va_start into a va_list and then call a companion function that accepts va_list directly (e.g., vprintf, vfprintf, vsnprintf). This is called variadic forwarding.
Given Data / Assumptions:
- Your wrapper is itself declared with ... after at least one named parameter.
- You have access to the appropriate v* function for the target routine.
- va_list is valid only between va_start and va_end; if you need to traverse twice, use va_copy where available.
Concept / Approach:Because you cannot synthesize a new “...” at run time, you forward by passing the va_list to a v* variant. Many standard families implement both forms for this reason: printf/vprintf, fprintf/vfprintf, snprintf/vsnprintf, etc.
Step-by-Step Solution:Define: void logf(const char fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); }If you must forward the list to two consumers, use va_copy before the first one and call va_end on each instance.
Verification / Alternative check:Check standard headers: prototypes for v functions accept va_list precisely to enable forwarding.
Why Other Options Are Wrong:Prohibiting passing va_list is incorrect; it is explicitly supported. Platform or integer-only restrictions do not apply. Skipping va_end is never acceptable.
Common Pitfalls:Reusing a va_list after it has been passed to a function that also iterates it; not using va_copy when multiple passes are needed.
Final Answer:Yes, by capturing with va_start and forwarding to a v* function (e.g., vprintf)