Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call (not define) a function with a variable number of arguments in C?

Is there any way to make this code shorter?

long call_f(int argc, long *argv) {
  switch (argc) {
    case 0:
      return f();
      break;
    case 1:
      return f(argv[0]);
      break;
    case 2:
      return f(argv[0], argv[1]);
      break;
    case 3:
      return f(argv[0], argv[1], argv[2]);
      break;
    case 4:
      return f(argv[0], argv[1], argv[2], argv[3]);
      break;
    // ...
  }
  return -1;
}
like image 347
Adrian Avatar asked Feb 27 '23 14:02

Adrian


1 Answers

No, there isn't any good way to do this. See here: http://c-faq.com/varargs/handoff.html

You can write a macro with token pasting to hide this behavior but that macro will be no simpler than this code, thus it's only worth writing if you have multiple functions like f() where you would otherwise have to duplicate this case statement.

like image 119
frankc Avatar answered Apr 06 '23 04:04

frankc