在所有我们看到的到目前为止功能参数,函数将数量必须预先知道(即使他们有默认值)。然而,有一些情况下,这将是能够数目可变的参数传递给一个函数有用。C语言提供了特殊的说明符被称为椭圆(又名“……”),让我们这样做。
由于椭圆是很少使用的,危险的,我们强烈建议避免使用,这部分可以被认为是选择性阅读。
使用椭圆函数,采取的形式return_type function_name(argument_list,……)。argument_list是一个或多个固定参数,就像正常功能的使用。省略号(表示为一排三个周期)必须在函数的最后一个参数。任何传递函数的实参必须与argument_list。椭圆捕获任何额外的参数(如果有)。虽然它不是很准确,它是想的椭圆作为一个数组保存任何额外的参数超出了那些在argument_list概念有用。
了解椭圆的最好的方式是通过例子。让我们写一个简单的程序,使用椭圆。让我们说我们要写一个函数,计算出一系列整数的平均值。我们就这样做:
include <cstdarg> // needed to use ellipses
// The ellipses must be the last parameter
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;
}
int main()
{
cout << FindAverage(5, 1, 2, 3, 4, 5) << endl;
cout << FindAverage(6, 1, 2, 3, 4, 5, 6) << endl;