0

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));

1 Answer 1

2

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] 

int foo(int a, int b, int c, int d)
{
   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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

This only works as long as the function always takes 4 arguments. The argument length can be variable.
@haley And how are you going to determine how many arguments a function has?
@jim mcnamara That's a nice solution, another macro trick i can remember.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.