LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   How to pass arguments to a function using a loop (http://www.linuxquestions.org/questions/programming-9/how-to-pass-arguments-to-a-function-using-a-loop-792406/)

10110111 03-01-2010 03:06 PM

How to pass arguments to a function using a loop
 
I need to pass a large number of arguments to a function which takes variable number of arguments, such as gtk_list_store_new. But it doesn't look nice if i write something like gtk_list_store_new(NUM,TYPE_A,TYPE_B,TYPE_C,...,TYPE_OMEGA); because of large number of arguments. And, it will be a trouble to change number of columns because of need to manually change arguments to large number of such functions.
So, how can i pass all the arguments to a function using a loop? Something like
Code:

for(i=0;i<NUM;i++)
{
 push_arg(args[i]);
}
call_function(func);

? Of course, i could just use asm code for this, but is there a portable way of doing so?

P.S. i mean C language.

nadroj 03-01-2010 03:33 PM

You can look into variable-length argument lists (example here), which is similar to how "printf", "scanf", etc, work. I've never implemented one of these functions, but a quick read on a different site says that there is no information about the type and number of subsequent arguments, so from that to me it seems you can pass your different types TYPE_A, TYPE_B, etc.

Alternatively, you can wrap the arguments in a structure (excuse any syntax errors)
Code:

struct arg_type
{
  char foo_set;
  int foo;

  char bar;
  char bar_set;
};

void f(struct arg_type args)
{
  if ( args.foo_set)
  {
    // do something with args.foo
  }

  // etc...
}

int main(void)
{
  struct arg_type args;
  args.foo_set = 1;
  args.foo = 42;

  f(args);
}

Maybe you could use a "void*[MAX_ARG_LENGTH]", and only populate the relevant index if that argument is "set" or "passed". For example
Code:

// map argument types to specific constant indices
const int INDEX_FOO = 2;
const int INDEX_BAR = 5;
// etc.
const itn MAX_ARG_LENGTH=42;

void foo(void* args[MAX_ARG_LENGTH])
{
  if (args[INDEX_FOO) != null)
  {
    // do something with arg 'foo'
  }

  // etc
}

int main(void)
{
  void* args[MAX_ARG_LENGTH];
  // "pass" value for only "foo"
  int foo = 1234;
  args[INDEX_FOO] = &foo;
  f(args);
}


10110111 03-01-2010 04:24 PM

Thanks for the reply. I found using your link that there's no portable way of passing variable list of arguments built on run time to functions such as f(a,...).
Anyway, i found that there does exist a function which will accept an array instead of explicit arguments - gtk_list_store_newv.


All times are GMT -5. The time now is 08:32 PM.