Home > Mobile >  pass 3 dots argument to another function
pass 3 dots argument to another function

Time:09-29

I have function called foo and that function takes ..., I want to pass all the argument that passed in ... to the function called oof, sample code:

#include <stdio.h>
#include <stdarg.h>


void oof(FILE * f, const char * fmt, ...){
    va_list args;

    va_start(args, fmt);
    vfprintf(f, fmt, args);
    va_end(args);
}

void foo(const char * fmt, ...){
    oof(stdout, fmt, ...); // how can I pass the 3 dots?
    // do other things in the function block
}

int main(int argc, char *argv[]){
    foo("Hello %s\n", "World");
}

I don't want to pass to oof a va_list, but the arguments themselves

CodePudding user response:

You need to change oof to accept a va_list and pass that.

void oof(FILE * f, const char * fmt, va_list args){
    vfprintf(f, fmt, args);
}

void foo(const char * fmt, ...){
    va_list args;

    va_start(args, fmt);
    oof(stderr, fmt, args);
    va_end(args);
}

CodePudding user response:

You cannot do this with a function but you can do this with a macro:

#define foo(...) oof(__VA_ARGS__)

There is still an issue.

Where do you get FILE *f argument from? Assuming it is stdout then define the macro as:

#define foo(...) oof(stdout, __VA_ARGS__)

CodePudding user response:

This is similar to dbush's answer (dbush should get the credit - do not accept my answer over theirs), but slightly modified because of OP's statement:

I don't want to pass to oof a va_list, but the arguments themselves

Because a va_list needs to be passed to something, I define a different function voof called by both oof and foo:

#include <stdio.h>
#include <stdarg.h>

void voof(FILE * f, const char * fmt, va_list args){

    vfprintf(f, fmt, args);
}

void oof(FILE * f, const char * fmt, ...){
    va_list args;

    va_start(args, fmt);
    voof(f, fmt, args);
    va_end(args);
}

void foo(const char * fmt, ...){
    va_list args;

    va_start(args, fmt);
    voof(stderr, fmt, args);
    va_end(args);
}

int main(int argc, char *argv[]){
    foo("Hello %s\n", "World");
}

foo and oof currently do the same thing, apart from the extra FILE * parameter in oof.

  • Related