我想在 c 中编写一个参数数量可变的函数..有人可以指导我吗..
最佳答案
这样的函数调用省略号:http://www.learncpp.com/cpp-tutorial/714-ellipses-and-why-to-avoid-them/
Because ellipses are rarely used, dangerous, and we strongly recommend avoiding their use, this section can be considered optional reading.
如果您仍然需要这样的函数,请看一下这个示例(重点是 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;
}
关于c - 如何用 C 语言编写带有可变参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15923834/