Forward an invocation of a variadic function in C

前端 未结 12 2444
悲哀的现实
悲哀的现实 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:18

    Not directly, however it is common (and you will find almost universally the case in the standard library) for variadic functions to come in pairs with a varargs style alternative function. e.g. printf/vprintf

    The v... functions take a va_list parameter, the implementation of which is often done with compiler specific 'macro magic', but you are guaranteed that calling the v... style function from a variadic function like this will work:

    #include 
    
    int m_printf(char *fmt, ...)
    {
        int ret;
    
        /* Declare a va_list type variable */
        va_list myargs;
    
        /* Initialise the va_list variable with the ... after fmt */
    
        va_start(myargs, fmt);
    
        /* Forward the '...' to vprintf */
        ret = vprintf(fmt, myargs);
    
        /* Clean up the va_list */
        va_end(myargs);
    
        return ret;
    }
    

    This should give you the effect that you are looking for.

    If you are considering writing a variadic library function you should also consider making a va_list style companion available as part of the library. As you can see from your question, it can be prove useful for your users.

提交回复
热议问题