如何在 C 中调用(不定义)具有可变数量参数的函数? [英] How can I call (not define) a function with a variable number of arguments in C?

查看:35
本文介绍了如何在 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;
}

推荐答案

不,没有什么好的方法可以做到这一点.看这里: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.

这篇关于如何在 C 中调用(不定义)具有可变数量参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆