如何在 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]);br...

有什么办法可以缩短这段代码?

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

推荐答案

不,没有什么好的方法可以做到这一点.看这里:http://c-faq.com/varargs/handoff.html

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

您可以编写一个带有标记粘贴的宏来隐藏此行为,但该宏不会比此代码简单,因此只有当您有多个函数(如 f())时才值得编写,否则您必须复制此 case 语句.

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.

阅读全文

相关推荐

最新文章