【问题标题】:How to write functions with variable arguments in C如何在 C 中编写带有可变参数的函数
【发布时间】:2013-04-02 04:12:41
【问题描述】:

我想在 c 中编写一个具有可变数量参数的函数..有人可以指导我..

【问题讨论】:

  • 如果你用谷歌搜索你的问题的标题,你会发现多篇文章。

标签: c user-defined-functions ellipsis


【解决方案1】:

此类函数调用省略号:http://www.learncpp.com/cpp-tutorial/714-ellipses-and-why-to-avoid-them/

因为省略号很少使用,很危险,我们强烈推荐 避免使用它们,本节可以视为可选阅读。

如果你仍然需要这样的功能,看看这个例子(重点是 va_list):

double FindAverage(int nCount, ...)
{
    long lSum = 0;

    // We access the ellipses through a va_list, so let's declare one
    va_list list;

    // We initialize the va_list using va_start.  The first parameter is
    // the list to initialize.  The second parameter is the last non-ellipse
    // parameter.
    va_start(list, nCount);

    // Loop nCount times
    for (int nArg=0; nArg < nCount; nArg++)
         // We use va_arg to get parameters out of our ellipses
         // The first parameter is the va_list we're using
         // The second parameter is the type of the parameter
         lSum += va_arg(list, int);

    // Cleanup the va_list when we're done.
    va_end(list);

    return static_cast<double>(lSum) / nCount;
}

【讨论】:

    【解决方案2】:
    return_type function name(int arg1,int arg2,....argn)
    {
    
    }
    

    你也可以参考,

    http://www.cprogramming.com/tutorial/c/lesson17.html

    【讨论】:

    • argn 在里面做什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    相关资源
    最近更新 更多