Take the 2-minute tour ×

Aside from hacking up some architecture/compiler dependent assembly, is it possible to do something like this using either straight C or a macro, and expand out a variable length array into the argument list:

void myFunc (int a, int b, int c, int d);
void myOtherFunc (int a, int b);

/* try to call them */
int args[4] = { 1, 2, 3, 4 };
myFunc (SOME_MAGIC (args));

int otherArgs[2] = { 1, 2 };
myOtherFunc (SOME_MAGIC (otherArgs));

Apologies if this is a duplicate; basically every variation on search terms I tried had a question about passing arrays between functions, not messing with the function stack.

It's OK to assume that the argument count passed to the function will always match the prototype. Otherwise, I suppose an argc/argv style thing is really the only way to go?

Another example, hopefully with a little more context:

const struct func_info table[NUM_FUNCS] = {
    { foo,             1,  true  },
    { bar,             2,  true  },
    // ...

struct func_info fi = table[function_id];
int args* = malloc (fi->argc * sizeof (int));
for (int i = 0; i < fi->argc; i++) {
    args[i] = GetArgument (i);

fi->func (SOME_MAGIC (args));
share|improve this question

1 Answer 1

You could use macros to expand args. Here is one way:

jim@jim-HP ~
$ cc smagic.c -o smagic

jim@jim-HP ~
$ ./smagic
a=1 b=2 c=3 d=4

#define SOME_MAGIC(args) args[0], args[1], args[2], args[3] 

   printf("a=%d b=%d c=%d d=%d\n", a,b,c,d);
   return a;
int main(int argc, char **argv)
    int args[]={1,2,3,4};

    foo( SOME_MAGIC(args) );
    return 0;
share|improve this answer
This only works as long as the function always takes 4 arguments. The argument length can be variable. –  halex Sep 25 '13 at 12:46
@haley And how are you going to determine how many arguments a function has? –  this Sep 25 '13 at 12:49
@jim mcnamara That's a nice solution, another macro trick i can remember. –  this Sep 25 '13 at 12:50
You would have to have several macros, one for each case. This is not a really elegant solution. Without writing some type of complex function dispatcher, I do not know of a way to do this. I don't have an example. –  jim mcnamara Sep 25 '13 at 12:55

Your Answer


