Forward an invocation of a variadic function in C

前端 未结 12 2713
悲哀的现实
悲哀的现实 2020-11-22 06:41

In C, is it possible to forward the invocation of a variadic function? As in,

int my_printf(char *fmt, ...) {
    fprintf(stderr, \"Calling printf with fmt %         


        
12条回答
  •  面向向阳花
    2020-11-22 07:25

    There are essentially three options.

    One is to not pass it on but to use the variadic implementation of your target function and not pass on the ellipses. The other one is to use a variadic macro. The third option is all the stuff i am missing.

    I usually go with option one since i feel like this is really easy to handle. Option two has a drawback because there are some limitations to calling variadic macros.

    Here is some example code:

    #include 
    #include 
    
    #define Option_VariadicMacro(f, ...)\
        printf("printing using format: %s", f);\
        printf(f, __VA_ARGS__)
    
    int Option_ResolveVariadicAndPassOn(const char * f, ... )
    {
        int r;
        va_list args;
    
        printf("printing using format: %s", f);
        va_start(args, f);
        r = vprintf(f, args);
        va_end(args);
        return r;
    }
    
    void main()
    {
        const char * f = "%s %s %s\n";
        const char * a = "One";
        const char * b = "Two";
        const char * c = "Three";
        printf("---- Normal Print ----\n");
        printf(f, a, b, c);
        printf("\n");
        printf("---- Option_VariadicMacro ----\n");
        Option_VariadicMacro(f, a, b, c);
        printf("\n");
        printf("---- Option_ResolveVariadicAndPassOn ----\n");
        Option_ResolveVariadicAndPassOn(f, a, b, c);
        printf("\n");
    }
    

提交回复
热议问题