Passing Variable Arguments to Functions with Variable Argument Lists
When working with functions that accept a variable number of arguments, it's often necessary to call one such function from another. However, directly passing arguments from one function to another can be problematic without modifying the target function if it's already in use elsewhere.
Consider the following example:
void example(int a, int b, ...); void exampleB(int b, ...);
In this scenario, example calls exampleB. However, the question arises: how can the variable arguments in example be passed to exampleB without modifying its original implementation?
Directly passing arguments from example to exampleB is not possible. Instead, an intermediary function that takes a va_list must be created:
#include <stdarg.h> static void exampleV(int b, va_list args); void exampleA(int a, int b, ...) // Renamed for consistency { va_list args; do_something(a); // Use argument a somehow va_start(args, b); exampleV(b, args); va_end(args); } void exampleB(int b, ...) { va_list args; va_start(args, b); exampleV(b, args); va_end(args); } static void exampleV(int b, va_list args) { ...whatever you planned to have exampleB do... ...except it calls neither va_start nor va_end... }
By introducing exampleV, which takes both b and args as arguments, exampleA can pass its variable arguments to exampleB without modifying its implementation. This intermediary function can then be used to perform the intended actions without disrupting the original implementation of exampleB.
The above is the detailed content of How to Pass Variable Arguments from One Function to Another with Variable Argument Lists?. For more information, please follow other related articles on the PHP Chinese website!