Passing Variable Arguments to Functions with Variable Argument Lists
Consider two functions with similar variable arguments:
void example(int a, int b, ...); void exampleB(int b, ...);
Suppose example calls exampleB, but without modifying exampleB (which is used elsewhere). How can we pass the variable arguments from example to exampleB?
Solution:
Directly passing arguments is not possible. Instead, we create a wrapper function that takes a va_list:
#include <stdarg.h> static void exampleV(int b, va_list args);
Modified Function exampleA:
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); }
Unmodified Function exampleB:
void exampleB(int b, ...) { va_list args; va_start(args, b); exampleV(b, args); va_end(args); }
Wrapper Function exampleV:
static void exampleV(int b, va_list args) { // Whatever `exampleB` was intended to do... // Except it doesn't call either `va_start` or `va_end`. }
This approach allows us to pass the variable arguments from example to exampleB without modifying the latter. The wrapper function exampleV does not call va_start or va_end, which ensures consistency with the existing usage of exampleB.
The above is the detailed content of How Can I Pass Variable Arguments from One Function to Another Without Modifying the Receiving Function?. For more information, please follow other related articles on the PHP Chinese website!